@powerhousedao/host-core 6.3.0-dev.3 → 6.3.0-dev.4
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.
- package/dist/{compound-CDrU3CLt.mjs → compound-DKi56SSx.mjs} +2 -1
- package/dist/{compound-CDrU3CLt.mjs.map → compound-DKi56SSx.mjs.map} +1 -1
- package/dist/index.d.mts +60 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +98 -2
- package/dist/index.mjs.map +1 -1
- package/dist/runners/compound.mjs +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compound-CDrU3CLt.mjs","names":["factory","valueAt","isRecord","isRecord"],"sources":["../src/plugins.ts","../src/plugins-resolve.ts","../src/drive-schema.ts","../src/host-schemas.ts","../src/resolve/walk.ts","../src/resolve/declared.ts","../src/resolve/removed-forms.ts","../src/env-substitution.ts","../src/resolve/plan.ts","../src/resolve/resolve.ts","../src/runner-resolver.ts","../src/host-loader.ts","../src/runner-args.ts","../src/run-record-schema.ts","../src/run-record.ts","../src/child-wrapper.ts","../src/placeholders.ts","../src/resolve/node.ts","../src/resolve/sources.ts","../src/runner-handle.ts","../src/compound.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/**\n * R1 — the host plugin framework (bridge-runners-to-plugins plan,\n * customization-references/host-core as the blueprint).\n *\n * A plugin is hooks + contributions; hooks are boot wiring (main realm only),\n * contributions are declarative, serializable surface. Host RUNTIMES define\n * the hook vocabulary and interleave their own wiring between stages — they\n * are never plugins themselves.\n *\n * host.js carries the COMPOSITION as `runner.plugins` entries:\n * string | { module, enabled?, verbs?, config? }\n * Presence is activation (enabled defaults true); `verbs` scopes an entry to\n * matching run verbs; `config` is validated against the plugin's declared\n * zod schema. Entries resolve from the PROJECT's dependency tree exactly\n * like runner modules.\n */\n\nexport class PluginError extends Error {\n constructor(message: string, hint?: string) {\n super(hint ? `${message}\\n Hint: ${hint}` : message);\n this.name = \"PluginError\";\n }\n}\n\n/* ------------------------------------------------------------------ entries */\n\nexport const pluginEntryObjectSchema = z.strictObject({\n module: z.string().min(1),\n /** Presence is activation BY DEFAULT; false is the explicit off-switch. */\n enabled: z.boolean().optional(),\n /** \"*\" (default) or the run verbs this entry is active for. */\n verbs: z\n .union([z.literal(\"*\"), z.array(z.string().min(1)).min(1)])\n .optional(),\n /** Validated against the plugin's declared configSchema at resolution. */\n config: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const pluginEntrySchema = z.union([\n z.string().min(1),\n pluginEntryObjectSchema,\n]);\n\n/** The validated (runtime) entry shape. Authors write `PluginEntry`\n * (host-types.ts), which types known plugins' configs. */\nexport type PluginEntryData = z.infer<typeof pluginEntrySchema>;\nexport type { PluginEntry } from \"./host-types.js\";\n\nexport interface NormalizedPluginEntry {\n module: string;\n enabled: boolean;\n verbs: \"*\" | string[];\n config: Record<string, unknown>;\n}\n\nexport function normalizePluginEntry(\n entry: PluginEntryData,\n): NormalizedPluginEntry {\n if (typeof entry === \"string\") {\n return { module: entry, enabled: true, verbs: \"*\", config: {} };\n }\n return {\n module: entry.module,\n enabled: entry.enabled ?? true,\n verbs: entry.verbs ?? \"*\",\n config: entry.config ?? {},\n };\n}\n\n/** Module is the identity key: a duplicate makes override targeting and\n * ordering ambiguous, so it fails loudly. */\nexport function normalizePluginEntries(\n entries: readonly PluginEntryData[],\n where: string,\n): NormalizedPluginEntry[] {\n const normalized = entries.map(normalizePluginEntry);\n const seen = new Set<string>();\n for (const entry of normalized) {\n if (seen.has(entry.module)) {\n throw new PluginError(\n `${where}: plugin \"${entry.module}\" is listed twice.`,\n \"Module specifiers are the identity key of a composition; a plugin meant to run twice needs distinct subpath specifiers.\",\n );\n }\n seen.add(entry.module);\n }\n return normalized;\n}\n\nexport function entryActiveForVerb(\n entry: NormalizedPluginEntry,\n verb: string,\n): boolean {\n if (!entry.enabled) return false;\n return entry.verbs === \"*\" || entry.verbs.includes(verb);\n}\n\n/* ---------------------------------------------------------------- hierarchy */\n\n/**\n * The appliesTo hierarchy. \"reactor\" is the base every reactor host extends;\n * \"compound\" is its own branch (plugins over the member set — e.g. the clint\n * proxy). Host runtimes register their id with a parent; compatibility walks\n * the parent chain.\n */\nconst HOST_TYPE_PARENTS: Record<string, string | null> = {\n reactor: null,\n compound: null,\n connect: \"reactor\",\n switchboard: \"reactor\",\n mastra: \"reactor\",\n};\n\nexport function registerHostType(id: string, parent: string | null): void {\n if (id in HOST_TYPE_PARENTS && HOST_TYPE_PARENTS[id] !== parent) {\n throw new PluginError(\n `Host type \"${id}\" is already registered with parent \"${String(HOST_TYPE_PARENTS[id])}\".`,\n );\n }\n HOST_TYPE_PARENTS[id] = parent;\n}\n\nexport function hostTypeSatisfies(\n hostType: string,\n appliesTo: string,\n): boolean {\n let current: string | null = hostType;\n while (current !== null) {\n if (current === appliesTo) return true;\n current = current in HOST_TYPE_PARENTS ? HOST_TYPE_PARENTS[current] : null;\n }\n return false;\n}\n\n/* ------------------------------------------------------------------- plugin */\n\n/** Hook kinds (v1 §2.2). The hook VOCABULARY is defined by host runtimes;\n * plugins implement subsets of it. */\nexport type Provide<T, C> = (ctx: C) => T | Promise<T>;\nexport type Transform<T, C> = (value: T, ctx: C) => T | Promise<T>;\nexport type Observe<C> = (ctx: C) => void | Promise<void>;\n\n/**\n * Core contributions — declarative, serializable, realm-crossing. Host\n * runtimes extend this with their own kinds (UI slots live in connect-host,\n * never here). `drives` entries use the drive declaration shape from\n * drives.ts; kept as unknown here to avoid a cycle — the merge is shape-blind.\n */\nexport interface Contributions {\n drives?: unknown[];\n packages?: string[];\n configDeclarations?: { name: string; type?: string; description?: string }[];\n [kind: string]: unknown[] | undefined;\n}\n\nexport interface HostPlugin<\n THooks = Record<string, unknown>,\n TConfig = unknown,\n> {\n /** Stable id; used in ordering, dependsOn, and every diagnostic. */\n name: string;\n /** Host-type requirement; the entry is rejected on a host outside the\n * hierarchy branch. Default: \"reactor\". */\n appliesTo?: string;\n /** Coarse ordering bucket (Vite-style). Default: \"normal\". */\n enforce?: \"pre\" | \"post\";\n /** Hard dependencies on OTHER PLUGINS — the host runtime is implied and\n * never named. Missing dependency or cycle fails boot naming both sides. */\n dependsOn?: string[];\n /** Declared config shape; entry config is validated against it. A plugin\n * without a schema accepts no config (passing one is a boot error). */\n configSchema?: z.ZodType<TConfig>;\n hooks?: Partial<THooks>;\n contributions?: Contributions;\n}\n\n/** A plugin module default-exports either a HostPlugin object (no config\n * accepted) or a factory `(config) => HostPlugin`. */\nexport type HostPluginModule<\n THooks = Record<string, unknown>,\n TConfig = unknown,\n> =\n | HostPlugin<THooks, TConfig>\n | ((config: TConfig) => HostPlugin<THooks, TConfig>);\n\nexport interface ResolvedPlugin<THooks = Record<string, unknown>> {\n entry: NormalizedPluginEntry;\n plugin: HostPlugin<THooks>;\n /** Provenance for contribution merge ordering. */\n provenance: \"built-in\" | \"local\" | \"dependency\";\n}\n\n/* ----------------------------------------------------------------- ordering */\n\n/** Registration order, bucketed pre → normal → post (stable within buckets),\n * then dependsOn topo-sorted within the bucketed order. */\nexport function resolveOrder<THooks>(\n plugins: readonly HostPlugin<THooks>[],\n): HostPlugin<THooks>[] {\n const buckets: Record<\"pre\" | \"normal\" | \"post\", HostPlugin<THooks>[]> = {\n pre: [],\n normal: [],\n post: [],\n };\n for (const plugin of plugins)\n buckets[plugin.enforce ?? \"normal\"].push(plugin);\n const bucketed = [...buckets.pre, ...buckets.normal, ...buckets.post];\n\n const byName = new Map(bucketed.map((p) => [p.name, p]));\n for (const plugin of bucketed) {\n for (const dep of plugin.dependsOn ?? []) {\n if (!byName.has(dep)) {\n throw new PluginError(\n `Plugin \"${plugin.name}\" depends on missing plugin \"${dep}\".`,\n \"dependsOn names PLUGINS only — the host runtime is implied and never named.\",\n );\n }\n }\n }\n\n const ordered: HostPlugin<THooks>[] = [];\n const state = new Map<string, \"visiting\" | \"done\">();\n const visit = (plugin: HostPlugin<THooks>, chain: string[]): void => {\n const mark = state.get(plugin.name);\n if (mark === \"done\") return;\n if (mark === \"visiting\") {\n throw new PluginError(\n `Plugin dependency cycle: ${[...chain, plugin.name].join(\" -> \")}.`,\n );\n }\n state.set(plugin.name, \"visiting\");\n for (const dep of plugin.dependsOn ?? []) {\n visit(byName.get(dep)!, [...chain, plugin.name]);\n }\n state.set(plugin.name, \"done\");\n ordered.push(plugin);\n };\n for (const plugin of bucketed) visit(plugin, []);\n return ordered;\n}\n\n/* -------------------------------------------------------------------- hooks */\n\nexport async function runProvideHook<T, C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n): Promise<T | undefined> {\n const impls = plugins.filter((p) => typeof p.hooks?.[name] === \"function\");\n if (impls.length > 1) {\n throw new PluginError(\n `Hook \"${name}\" is provided by ${impls.map((p) => `\"${p.name}\"`).join(\" and \")} — provide hooks have one winner.`,\n );\n }\n const impl = impls[0]?.hooks?.[name] as Provide<T, C> | undefined;\n return impl ? await impl(ctx) : undefined;\n}\n\nexport async function runTransformHook<T, C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n seed: T,\n): Promise<T> {\n let value = seed;\n for (const plugin of plugins) {\n const impl = plugin.hooks?.[name] as Transform<T, C> | undefined;\n if (typeof impl === \"function\") value = await impl(value, ctx);\n }\n return value;\n}\n\n/** Sequential observe, in plugin order — for lifecycle moments whose order\n * is load-bearing (teardown: the switchboard stops privacy before workflows\n * before the api, per the carve map). */\nexport async function runObserveHookSequential<C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n): Promise<void> {\n for (const plugin of plugins) {\n const impl = plugin.hooks?.[name] as Observe<C> | undefined;\n if (typeof impl === \"function\") await impl(ctx);\n }\n}\n\nexport async function runObserveHook<C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n): Promise<void> {\n await Promise.all(\n plugins.map(async (plugin) => {\n const impl = plugin.hooks?.[name] as Observe<C> | undefined;\n if (typeof impl === \"function\") await impl(ctx);\n }),\n );\n}\n\n/* ------------------------------------------------------------ contributions */\n\nexport interface ContributionSource {\n pluginName: string;\n provenance: \"built-in\" | \"local\" | \"dependency\";\n}\n\nexport interface MergedContribution<T = unknown> {\n value: T;\n source: ContributionSource;\n}\n\n/** Array kinds concatenate in provenance-then-order sequence (built-in first,\n * so later sources read as overrides where consumers want last-wins). */\nexport function mergeContributions(\n resolved: readonly {\n plugin: HostPlugin;\n provenance: ContributionSource[\"provenance\"];\n }[],\n): Record<string, MergedContribution[]> {\n const rank: Record<ContributionSource[\"provenance\"], number> = {\n \"built-in\": 0,\n local: 1,\n dependency: 2,\n };\n const sorted = [...resolved].sort(\n (a, b) => rank[a.provenance] - rank[b.provenance],\n );\n const merged: Record<string, MergedContribution[]> = {};\n for (const { plugin, provenance } of sorted) {\n for (const [kind, values] of Object.entries(plugin.contributions ?? {})) {\n if (!values) continue;\n const bucket = (merged[kind] ??= []);\n for (const value of values) {\n bucket.push({ value, source: { pluginName: plugin.name, provenance } });\n }\n }\n }\n return merged;\n}\n","import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { z } from \"zod\";\nimport {\n entryActiveForVerb,\n hostTypeSatisfies,\n normalizePluginEntries,\n PluginError,\n type HostPlugin,\n type PluginEntryData,\n type ResolvedPlugin,\n} from \"./plugins.js\";\n\n/**\n * NODE-ONLY plugin resolution (split from plugins.ts so the pure runner core\n * stays browser-safe for ConnectCore — R3). Resolves host.js entries from the\n * PROJECT dependency tree, exactly like runner modules.\n */\n\nfunction isHostPluginShape(value: unknown): value is HostPlugin {\n return (\n value !== null &&\n typeof value === \"object\" &&\n typeof (value as HostPlugin).name === \"string\"\n );\n}\n\n/**\n * Resolve host.js plugin entries into live plugins for one host boot:\n * verb-filter → module resolution from the project tree (default condition,\n * like runners) → factory/object contract → config validation → appliesTo.\n */\nexport async function resolveHostPlugins<THooks = Record<string, unknown>>(\n projectRoot: string,\n hostType: string,\n verb: string,\n entries: readonly PluginEntryData[],\n where: string,\n): Promise<ResolvedPlugin<THooks>[]> {\n const normalized = normalizePluginEntries(entries, where);\n const projectRequire = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n\n const resolved: ResolvedPlugin<THooks>[] = [];\n for (const entry of normalized) {\n if (!entryActiveForVerb(entry, verb)) continue;\n\n let file: string;\n try {\n file = projectRequire.resolve(entry.module);\n } catch {\n throw new PluginError(\n `${where}: cannot resolve plugin \"${entry.module}\" from ${projectRoot}.`,\n \"Plugins resolve from the project dependency tree, exactly like runner modules.\",\n );\n }\n const module = (await import(pathToFileURL(file).href)) as {\n default?: unknown;\n };\n const exported = module.default;\n\n let plugin: HostPlugin<THooks>;\n if (typeof exported === \"function\") {\n const factory = exported as (config: unknown) => HostPlugin<THooks>;\n plugin = factory(entry.config);\n } else if (isHostPluginShape(exported)) {\n if (Object.keys(entry.config).length > 0 && !exported.configSchema) {\n throw new PluginError(\n `${where}: plugin \"${entry.module}\" takes no config, but the entry passes one.`,\n );\n }\n plugin = exported as HostPlugin<THooks>;\n } else {\n throw new PluginError(\n `${where}: \"${entry.module}\" does not default-export a plugin object or factory.`,\n \"Export `{ name, hooks?, contributions? }` or `(config) => plugin`.\",\n );\n }\n\n if (plugin.configSchema) {\n const parsed = plugin.configSchema.safeParse(entry.config);\n if (!parsed.success) {\n throw new PluginError(\n `${where}: config for plugin \"${plugin.name}\" is invalid:\\n` +\n z.prettifyError(parsed.error),\n );\n }\n }\n\n const appliesTo = plugin.appliesTo ?? \"reactor\";\n if (!hostTypeSatisfies(hostType, appliesTo)) {\n throw new PluginError(\n `${where}: plugin \"${plugin.name}\" applies to \"${appliesTo}\" hosts, but this host is \"${hostType}\".`,\n );\n }\n\n resolved.push({ entry, plugin, provenance: \"dependency\" });\n }\n return resolved;\n}\n\n/** A drive a plugin contributes: its declaration (drives.ts shape, validated\n * by the consumer) and the plugin it came from. */\nexport interface ContributedDrive {\n declaration: Record<string, unknown>;\n source: string;\n}\n\nexport interface PluginContributionsPlan {\n drives: ContributedDrive[];\n /** Entries whose module the project tree cannot resolve (e.g. Connect's\n * browser built-ins, which have no Node-resolvable identity module). */\n unresolved: string[];\n}\n\n/**\n * LENIENT resolution for diagnostics (`ph run <host> --explain drives`):\n * collects the drive contributions of the entries active for `verb`. Unlike\n * resolveHostPlugins it does not know the host type (so appliesTo is not\n * checked) and does not fail on a specifier the project tree cannot resolve\n * — the entry is listed under `unresolved` instead. Config is still validated\n * against the plugin's schema, so a bad entry surfaces here too.\n */\nexport async function resolvePluginContributions(\n projectRoot: string,\n verb: string,\n entries: readonly PluginEntryData[],\n where: string,\n): Promise<PluginContributionsPlan> {\n const normalized = normalizePluginEntries(entries, where);\n const projectRequire = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n const plan: PluginContributionsPlan = { drives: [], unresolved: [] };\n for (const entry of normalized) {\n if (!entryActiveForVerb(entry, verb)) continue;\n let file: string;\n try {\n file = projectRequire.resolve(entry.module);\n } catch {\n plan.unresolved.push(entry.module);\n continue;\n }\n const module = (await import(pathToFileURL(file).href)) as {\n default?: unknown;\n };\n const exported = module.default;\n let plugin: HostPlugin;\n if (typeof exported === \"function\") {\n plugin = (exported as (config: unknown) => HostPlugin)(entry.config);\n } else if (isHostPluginShape(exported)) {\n plugin = exported;\n } else {\n plan.unresolved.push(entry.module);\n continue;\n }\n if (plugin.configSchema) {\n const parsed = plugin.configSchema.safeParse(entry.config);\n if (!parsed.success) {\n throw new PluginError(\n `${where}: config for plugin \"${plugin.name}\" is invalid:\\n` +\n z.prettifyError(parsed.error),\n );\n }\n }\n for (const declaration of plugin.contributions?.drives ?? []) {\n plan.drives.push({\n declaration: declaration as Record<string, unknown>,\n source: plugin.name,\n });\n }\n }\n return plan;\n}\n\n/* -------------------------------------------------------------- dead config */\n\n/** One Connect config value a built-in Connect plugin owns. */\nexport interface OwnedConfigSlice {\n /** Dot path inside the connect config block, e.g. \"drives.allowAddDrive\". */\n path: string;\n /** What Connect serves at `path` while the owning plugin is absent from a\n * declared composition (apps/connect plugin-host.ts zeroAbsentSlices). */\n absent: unknown;\n /** The owning plugin's entry config key that sets this value, when the\n * plugin takes it as config; omitted where presence alone is the switch. */\n entryKey?: string;\n}\n\nexport interface ConnectPluginSlices {\n slices: OwnedConfigSlice[];\n /** A slice whose unset or `absent` value leaves every slice of this plugin\n * inert (OpenPanel tracking does nothing without a clientId), so nothing\n * of it is reported as dead. */\n inertUnless?: string;\n}\n\n/**\n * The connect config slices each built-in Connect plugin owns, by specifier\n * (typed-host-configs 1.6). Under a declared composition Connect zeroes a\n * slice whose plugin is absent — presence is activation — so an authored\n * value there is dead config. Connect's built-ins are browser modules with no\n * Node-resolvable identity, so their ownership is declared here as data; a\n * Connect test pins it to plugin-host's zeroing.\n */\nexport const CONNECT_PLUGIN_OWNED_SLICES: Readonly<\n Record<string, ConnectPluginSlices>\n> = {\n \"@powerhousedao/connect/plugins/generic\": {\n slices: [\n {\n path: \"drives.allowAddDrive\",\n absent: false,\n entryKey: \"allowAddDrive\",\n },\n {\n path: \"drives.sections\",\n absent: {\n remote: { enabled: false, allowAdd: false, allowDelete: false },\n local: { enabled: false, allowAdd: false, allowDelete: false },\n },\n entryKey: \"sections\",\n },\n { path: \"drives.icons\", absent: null, entryKey: \"icons\" },\n { path: \"home.background\", absent: null, entryKey: \"homeBackground\" },\n ],\n },\n \"@powerhousedao/connect/plugins/sentry\": {\n slices: [{ path: \"sentry.dsn\", absent: null, entryKey: \"dsn\" }],\n },\n \"@powerhousedao/connect/plugins/openpanel\": {\n slices: [\n { path: \"openPanel.clientId\", absent: \"\", entryKey: \"clientId\" },\n {\n path: \"openPanel.trackUiEvents\",\n absent: false,\n entryKey: \"trackUiEvents\",\n },\n {\n path: \"openPanel.trackOperations\",\n absent: false,\n entryKey: \"trackOperations\",\n },\n ],\n inertUnless: \"openPanel.clientId\",\n },\n \"@powerhousedao/connect/plugins/assistant\": {\n slices: [{ path: \"ai.assistantEnabled\", absent: false }],\n },\n \"@powerhousedao/vetra-studio/connect\": {\n slices: [{ path: \"app.studioMode\", absent: false }],\n },\n \"@powerhousedao/connect/plugins/workflows\": {\n slices: [{ path: \"app.workflowsEnabled\", absent: false }],\n },\n};\n\nexport interface DeadConfigWarning {\n /** Dot path inside the connect config block. */\n path: string;\n /** The authored value. */\n value: unknown;\n /** What Connect serves instead. */\n served: unknown;\n /** The specifier of the plugin that owns the slice. */\n owner: string;\n message: string;\n}\n\nfunction valueAt(root: unknown, dotted: string): unknown {\n let current = root;\n for (const key of dotted.split(\".\")) {\n if (current === null || typeof current !== \"object\") return undefined;\n current = (current as Record<string, unknown>)[key];\n }\n return current;\n}\n\n/** Whether Connect already serves what the author wrote: every authored leaf\n * equals the served one. An unset leaf asks for nothing, so a partial object\n * (`sections: { remote: { enabled: false } }`) is satisfied by the zeroed\n * slice. */\nfunction alreadyServed(authored: unknown, served: unknown): boolean {\n if (authored === undefined || Object.is(authored, served)) return true;\n if (\n authored === null ||\n served === null ||\n typeof authored !== \"object\" ||\n typeof served !== \"object\" ||\n Array.isArray(authored) !== Array.isArray(served)\n ) {\n return false;\n }\n if (\n Array.isArray(authored) &&\n authored.length !== (served as unknown[]).length\n ) {\n return false;\n }\n const want = authored as Record<string, unknown>;\n const have = served as Record<string, unknown>;\n return Object.keys(want).every((key) => alreadyServed(want[key], have[key]));\n}\n\n/**\n * The composition that serves `config` as Connect serves it with none, for a\n * host that declares no `runner.plugins`. `config` is the connect block\n * Connect would be served without a composition.\n *\n * A built-in configured through its entry is always in it, its entry holding\n * the values `config` has at the slices it owns: composed in, the plugin\n * serves those values again (an unset one falls back to the same default).\n * A built-in whose presence is its switch is in it only where `config`\n * already has that switch on, since composing it in would turn it on.\n */\nexport function defaultConnectComposition(\n config: Record<string, unknown> | undefined,\n): { module: string; config: Record<string, unknown> }[] {\n const composition: { module: string; config: Record<string, unknown> }[] = [];\n for (const [module, { slices }] of Object.entries(\n CONNECT_PLUGIN_OWNED_SLICES,\n )) {\n const entry: Record<string, unknown> = {};\n let configured = false;\n let switchedOn = false;\n for (const { path: slicePath, absent, entryKey } of slices) {\n const value = valueAt(config, slicePath);\n if (entryKey === undefined) {\n switchedOn ||= !alreadyServed(value, absent);\n continue;\n }\n configured = true;\n if (value !== undefined && value !== null) entry[entryKey] = value;\n }\n if (configured || switchedOn) composition.push({ module, config: entry });\n }\n return composition;\n}\n\n/**\n * Dead-config warnings for a Connect host (typed-host-configs 1.6): an\n * authored connect config value whose owning plugin is not in the\n * composition active for `verb`. Connect zeroes such a slice, so the value\n * has no effect — e.g. Sektar's `connect.drives.allowAddDrive: true` without\n * the generic plugin.\n *\n * Nothing is reported when the host declares no composition\n * (`runner.plugins` absent: the classic boot serves the config as is), or\n * when Connect already serves every leaf of the authored value. Warnings, not\n * errors: the host still boots, it just does not do what the value says.\n */\nexport function findDeadConnectConfig(\n config: Record<string, unknown> | undefined,\n entries: readonly PluginEntryData[] | undefined,\n verb: string,\n where: string,\n): DeadConfigWarning[] {\n if (!config || entries === undefined) return [];\n const active = new Set(\n normalizePluginEntries(entries, where)\n .filter((entry) => entryActiveForVerb(entry, verb))\n .map((entry) => entry.module),\n );\n const warnings: DeadConfigWarning[] = [];\n for (const [owner, { slices, inertUnless }] of Object.entries(\n CONNECT_PLUGIN_OWNED_SLICES,\n )) {\n if (active.has(owner)) continue;\n if (inertUnless !== undefined) {\n const gate = slices.find((slice) => slice.path === inertUnless);\n const gateValue = valueAt(config, inertUnless);\n if (alreadyServed(gateValue, gate?.absent)) {\n continue;\n }\n }\n for (const { path: slicePath, absent, entryKey } of slices) {\n const value = valueAt(config, slicePath);\n if (alreadyServed(value, absent)) continue;\n const move =\n entryKey === undefined\n ? `compose \"${owner}\" (presence is the switch)`\n : `compose \"${owner}\" and set \\`${entryKey}\\` in its entry config`;\n warnings.push({\n path: slicePath,\n value,\n served: absent,\n owner,\n message:\n `${where}: config.${slicePath} is dead config: it is owned by plugin \"${owner}\", ` +\n `which this host does not compose for verb \"${verb}\", so Connect serves ${JSON.stringify(absent)} instead of ${JSON.stringify(value)}.` +\n `\\n Hint: ${move}, or delete the value.`,\n });\n }\n }\n return warnings;\n}\n","import { z } from \"zod\";\nimport { tokenable, type TokenableSchema } from \"./tokens.js\";\n\n/**\n * The schema half of drives.ts, zod only so `./schema` stays neutral.\n * - slug: the SEEDING KEY (idempotence); id optional (stable identity).\n * - preferredEditor: stored at header.meta.preferredEditor; Connect config's\n * `app` is the legacy alias.\n * - remote.url: a drive served elsewhere; local fields are ignored for it.\n * Token-able (`$output` on a producer's `drives.<slug>.url`).\n */\nexport function buildDriveDeclarationSchema(\n urlField: (schema: z.ZodString) => TokenableSchema<z.ZodString>,\n) {\n return z.strictObject({\n slug: z.string().min(1),\n id: z.string().min(1).optional(),\n /** Derive the id from the project path, like generateProjectDriveId — the\n * same ids classic `ph vetra` produces. `true` serves the drive under the\n * hashed slug too (the vetra drive's slug IS its hashed id); `\"id\"` hashes\n * only the id and keeps the declared slug (the classic Workflows drive:\n * `/d/workflows`, id `workflows-<hash>`). */\n projectHash: z.union([z.boolean(), z.literal(\"id\")]).optional(),\n /** What a missing drive is created as. Default powerhouse/document-drive. */\n documentType: z\n .enum([\"powerhouse/document-drive\", \"powerhouse/reactor-drive\"])\n .optional(),\n name: z.string().min(1).optional(),\n icon: z.string().optional(),\n preferredEditor: z.string().optional(),\n sharingType: z.enum([\"public\", \"private\", \"shared\"]).optional(),\n availableOffline: z.boolean().optional(),\n remote: z.strictObject({ url: urlField(z.string().min(1)) }).optional(),\n });\n}\n\nexport const driveDeclarationSchema = buildDriveDeclarationSchema(tokenable);\n\nexport type DriveDeclaration = z.infer<typeof driveDeclarationSchema>;\n\nexport const drivesSchema = z.array(driveDeclarationSchema);\n\n/** The project-hashed drive id (`${slug}-${sha256(projectRoot)[0..8]}`) with\n * the hash function injected, so neutral consumers (a browser monitor) can\n * pass `crypto.subtle`-derived or precomputed hex. drives.ts binds it to\n * node:crypto as `projectDriveId`. */\nexport function projectDriveIdWith(\n sha256Hex: (input: string) => string,\n projectRoot: string,\n slug: string,\n): string {\n return `${slug}-${sha256Hex(projectRoot).substring(0, 8)}`;\n}\n","import { switchboardOfDrive } from \"@powerhousedao/shared/host-tokens\";\nimport { isOriginPlaceholderUrl } from \"@powerhousedao/shared/connect/origin-placeholder\";\nimport { z } from \"zod\";\nimport { buildDriveDeclarationSchema } from \"./drive-schema.js\";\nimport { pluginEntrySchema } from \"./plugins.js\";\nimport {\n envTokenable,\n tokenable,\n type EnvToken,\n type TokenableSchema,\n type TokenMode,\n} from \"./tokens.js\";\n\n/**\n * The zod single source for host.js blocks (typed-host-configs G1). Every\n * host type is z.input/z.output of these schemas; nothing is hand-mirrored.\n * Top-level host objects and the `reactor` block are STRICT (a typo fails);\n * `runner` stays loose until each runner declares its options (T2), and\n * `config` is runner-defined.\n *\n * Token-able fields (typed-host-configs 3.5): `reactor.backends.*.remote.url`\n * (required, a switchboard drive address), `reactor.drives` (whole list, e.g. `$map`),\n * `reactor.drives[].remote.url` and `storage.dataDir` (`$env` only). Their z.input admits tokens, their z.output is the resolved type.\n */\n\n/** A host's `name` keys its run record, `.ph/run/<name>.json`, so it must be\n * one safe path segment. */\nexport const HOST_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\nexport const HOST_NAME_MAX_LENGTH = 128;\nexport const HOST_NAME_MESSAGE =\n \"A host name is used as a file name, so use only letters, digits, '.', '_' and '-', start with a letter or digit, and keep it to 128 characters.\";\nexport const hostNameSchema = z\n .string()\n .min(1)\n .max(HOST_NAME_MAX_LENGTH, HOST_NAME_MESSAGE)\n .regex(HOST_NAME_PATTERN, HOST_NAME_MESSAGE);\n\n/**\n * A URL, or one written against the page origin (`${origin}/graphql`): the\n * browser resolves the placeholder when it loads Connect's config, for a\n * member whose own server proxies the switchboard's paths.\n */\nexport const originOrUrlSchema = z.union([\n z.url(),\n z.string().refine(isOriginPlaceholderUrl, {\n message: \"a URL, or ${origin}/<path> for a proxied sibling\",\n }),\n]);\n\nexport const profileSchema = z.strictObject({\n appId: z.string().min(1).optional(),\n name: z.string().min(1).optional(),\n description: z.string().optional(),\n icon: z.string().optional(),\n});\n\nexport const reactorProtocolSchema = z.strictObject({\n featureFlags: z\n .strictObject({\n documentDecisions: z.boolean().optional(),\n authEnforcement: z.boolean().optional(),\n authGroups: z.boolean().optional(),\n authConditions: z.boolean().optional(),\n undoV3: z.boolean().optional(),\n })\n .optional(),\n createSignaturePolicy: z.enum([\"legacy\", \"v2-required\"]).optional(),\n unsupportedStoredDocuments: z.enum([\"refuse\", \"read-only\"]).optional(),\n});\n\nexport const runnerKindSchema = z.enum([\"reactor\", \"compound\"]);\nexport type RunnerKind = z.infer<typeof runnerKindSchema>;\n\nexport const reactorBackendKindSchema = z.enum([\n \"in-process\",\n \"worker\",\n \"remote\",\n]);\n\n// Path-equality for the one-dir guard: pure string normalisation (the host\n// core stays Node-free); the server repeats the check with path.resolve.\nconst samePath = (a: string, b: string): boolean => {\n const norm = (p: string) =>\n p.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\").replace(/^\\.\\//, \"\");\n return norm(a) === norm(b);\n};\n\n/** Compound wiring: the generic compound runner's `config` block.\n * (`projectDrivesIntoConnect` and `drivesPublicBase` were removed in T3: a\n * member consumes another member's drives through `$output` tokens.) */\nexport const compoundWiringSchema = z.strictObject({\n /** Member start order; must name declared children and agree with the\n * output-token dependencies (resolve/plan.ts). Optional: without it the\n * order is derived from the tokens. Unnamed members start after the named\n * ones, in declaration order. */\n startOrder: z.array(z.string().min(1)).optional(),\n /** Write .ph/run/<host>.json (default true). */\n runtimeRecord: z.boolean().optional(),\n /** Patch the baked CSP for the runtime registry on a served Connect\n * member (forwarded as `runner.cspRegistrySync` to every member whose\n * runner is `@powerhousedao/ph-cli/runners/connect`). */\n cspRegistrySync: z.boolean().optional(),\n});\n\n/** `config.startOrder ⊆ keys(children)`, checked where both are visible.\n * Apply it LAST (`.superRefine(refineStartOrder)`) to a runner's final host\n * schema: zod refuses to `.extend()` a refined object. */\nexport function refineStartOrder(\n host: { children: Record<string, unknown>; config?: Record<string, unknown> },\n ctx: z.RefinementCtx,\n): void {\n const startOrder = host.config?.startOrder;\n if (!Array.isArray(startOrder)) return;\n const members = Object.keys(host.children);\n startOrder.forEach((name: unknown, index) => {\n if (startOrder.indexOf(name) !== index) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"config\", \"startOrder\", index],\n message: `startOrder names \"${String(name)}\" twice; each member starts once.`,\n });\n return;\n }\n if (typeof name === \"string\" && members.includes(name)) return;\n ctx.addIssue({\n code: \"custom\",\n path: [\"config\", \"startOrder\", index],\n message: `startOrder names \"${String(name)}\", which is not a member. Members: ${members.join(\", \") || \"(none)\"}.`,\n });\n });\n}\n\n/** How a schema set wraps its token-able fields. Both modes share one static\n * type (declared input, resolved output); they differ at runtime only. */\ninterface FieldWrappers {\n any: <S extends z.ZodType>(schema: S) => TokenableSchema<S>;\n env: <S extends z.ZodType>(schema: S) => TokenableSchema<S, EnvToken>;\n}\n\nconst ALLOW_TOKENS: FieldWrappers = { any: tokenable, env: envTokenable };\n// A one-option union: the same validation as `schema`, typed like the\n// \"allow\" wrappers so both modes share HostSchemas.\nconst FORBID_TOKENS: FieldWrappers = {\n any: (schema) => z.union([schema]),\n env: (schema) => z.union([schema]),\n};\n\n/** The replacement a non-drive `remote.url` message names. */\nfunction useDriveUrl(host = \"switchboard\", member?: string): string {\n const memberPart = member ? `, member: \"${member}\"` : \"\";\n return (\n `remote: { url: ${host}.drives.<slug>.url } with ${host} from ../${host}/outputs.js, ` +\n `or remote: { url: { $output: { host: \"${host}\"${memberPart}, path: [\"drives\", \"<slug>\", \"url\"] } } }`\n );\n}\n\n/** The `$output` of a declared `remote.url` that reads `endpoints.graphql`. */\nfunction endpointsGraphqlRef(\n url: unknown,\n): { host: string; member?: string } | undefined {\n if (typeof url !== \"object\" || url === null || !(\"$output\" in url)) {\n return undefined;\n }\n const ref = (url as { $output: unknown }).$output;\n if (typeof ref !== \"object\" || ref === null) return undefined;\n const { host, member, path } = ref as Record<string, unknown>;\n if (typeof host !== \"string\" || !Array.isArray(path)) return undefined;\n if (path.join(\".\") !== \"endpoints.graphql\") return undefined;\n return { host, ...(typeof member === \"string\" ? { member } : {}) };\n}\n\n/** The slug a drive link names: a `drives.<slug>.url` token's slug or a\n * literal address's served slug; undefined when only runtime knows it. */\nfunction linkedSlug(url: unknown): string | undefined {\n if (typeof url === \"string\") return switchboardOfDrive(url)?.slug;\n const ref =\n typeof url === \"object\" && url !== null && \"$output\" in url\n ? (url as { $output: { path?: unknown } }).$output\n : undefined;\n const path = Array.isArray(ref?.path) ? (ref.path as unknown[]) : [];\n return path.length === 3 &&\n path[0] === \"drives\" &&\n typeof path[1] === \"string\" &&\n path[2] === \"url\"\n ? path[1]\n : undefined;\n}\n\ninterface DeclaredReactorHost {\n runner?: { plugins?: unknown };\n config?: unknown;\n reactor?: {\n backends?: Record<string, { kind: string; remote?: { url: unknown } }>;\n placement?: {\n primary?: string;\n drives?: Record<string, string>;\n newDrives?: string;\n };\n drives?: unknown;\n };\n}\n\n/** The drives a declared host names (home drives, `reactor.drives`, plugin\n * `config.drive` links), or undefined when one is known only at runtime. */\nfunction knownDriveSlugs(host: DeclaredReactorHost): string[] | undefined {\n const reactor = host.reactor ?? {};\n const slugs: string[] = [];\n for (const backend of Object.values(reactor.backends ?? {})) {\n if (backend.kind !== \"remote\") continue;\n const slug = linkedSlug(backend.remote?.url);\n if (slug === undefined) return undefined;\n slugs.push(slug);\n }\n if (reactor.drives !== undefined) {\n if (!Array.isArray(reactor.drives)) return undefined;\n for (const drive of reactor.drives as { slug?: unknown }[]) {\n if (typeof drive.slug === \"string\") slugs.push(drive.slug);\n }\n }\n const plugins = Array.isArray(host.runner?.plugins)\n ? (host.runner.plugins as unknown[])\n : [];\n for (const entry of plugins) {\n const config =\n typeof entry === \"object\" && entry !== null && \"config\" in entry\n ? (entry as { config: unknown }).config\n : undefined;\n if (typeof config !== \"object\" || config === null) continue;\n if (!(\"drive\" in config) || config.drive === undefined) continue;\n const slug = linkedSlug(config.drive);\n if (slug === undefined) return undefined;\n slugs.push(slug);\n }\n for (const drive of connectDefaultDrives(host.config)) {\n if (typeof drive !== \"object\" || drive === null || !(\"url\" in drive)) {\n continue;\n }\n const slug = linkedSlug(drive.url);\n if (slug === undefined) return undefined;\n slugs.push(slug);\n }\n return slugs;\n}\n\n/** A Connect host's `config.drives.defaultDrives`, unchecked. */\nfunction connectDefaultDrives(config: unknown): unknown[] {\n const drives =\n typeof config === \"object\" && config !== null && \"drives\" in config\n ? (config as { drives: unknown }).drives\n : undefined;\n const list =\n typeof drives === \"object\" && drives !== null && \"defaultDrives\" in drives\n ? (drives as { defaultDrives: unknown }).defaultDrives\n : undefined;\n return Array.isArray(list) ? list : [];\n}\n\n/** Declared form, at host level so plugin drives are seen: a placement key\n * must name a drive the host names, when every drive is knowable. A host\n * with no remote backend is not checked: its plugins may contribute drives\n * (a switchboard's workflows drive) that no field names. */\nfunction refineDeclaredPlacementKeys(\n host: DeclaredReactorHost,\n ctx: z.RefinementCtx,\n): void {\n const placed = Object.keys(host.reactor?.placement?.drives ?? {});\n if (placed.length === 0) return;\n const remote = Object.values(host.reactor?.backends ?? {}).some(\n (b) => b.kind === \"remote\",\n );\n if (!remote) return;\n const known = knownDriveSlugs(host);\n if (!known) return;\n // A literal address may carry the hashed slug of a `projectHash` drive.\n const names = (slug: string, served: string) =>\n served === slug ||\n (served.startsWith(`${slug}-`) &&\n /^[0-9a-f]{8}$/.test(served.slice(slug.length + 1)));\n for (const slug of placed) {\n if (known.some((served) => names(slug, served))) continue;\n ctx.addIssue({\n code: \"custom\",\n path: [\"reactor\", \"placement\", \"drives\", slug],\n message: `placement.drives.${slug} names no drive this host links to or declares (${[...new Set(known)].join(\", \") || \"none\"}).`,\n });\n }\n}\n\ninterface ResolvedReactorBlock {\n backends?: Record<string, { kind: string; remote?: { url: unknown } }>;\n placement?: { drives?: Record<string, string> };\n drives?: unknown;\n}\n\n/** Resolved-form checks across backends, drives and placement: one base is\n * one remote backend, and a drive placed on a remote is on its switchboard. */\nfunction refineResolvedReactor(\n reactor: ResolvedReactorBlock,\n ctx: z.RefinementCtx,\n): void {\n const backends = reactor.backends ?? {};\n const baseOf = new Map<string, string>();\n const byBase = new Map<string, string>();\n // Every switchboard a slug is linked on: one slug on two is ambiguous.\n const linked = new Map<string, Set<string>>();\n const link = (slug: string, base: string) =>\n linked.set(slug, (linked.get(slug) ?? new Set()).add(base));\n for (const [name, backend] of Object.entries(backends)) {\n const url = backend.remote?.url;\n if (backend.kind !== \"remote\" || typeof url !== \"string\") continue;\n const home = switchboardOfDrive(url);\n if (!home) continue;\n baseOf.set(name, home.base);\n link(home.slug, home.base);\n const first = byBase.get(home.base);\n if (first === undefined) {\n byBase.set(home.base, name);\n continue;\n }\n ctx.addIssue({\n code: \"custom\",\n path: [\"backends\", name, \"remote\", \"url\"],\n message: `backends \"${first}\" and \"${name}\" both open drives on the same switchboard (${home.base}). Keep \"${first}\", and list the second drive under reactor.drives with its remote.url instead.`,\n });\n }\n\n const kept = new Set<string>();\n const declared = Array.isArray(reactor.drives)\n ? (reactor.drives as { slug: string; remote?: { url: string } }[])\n : [];\n declared.forEach((drive, index) => {\n if (!drive.remote) {\n kept.add(drive.slug);\n return;\n }\n const at = switchboardOfDrive(drive.remote.url);\n // An empty url already fails the field's own check.\n if (at || drive.remote.url === \"\") {\n if (at) link(drive.slug, at.base);\n return;\n }\n ctx.addIssue({\n code: \"custom\",\n path: [\"drives\", index, \"remote\", \"url\"],\n message: `remote.url must be a switchboard drive address (<switchboard>/d/<slug>), not ${drive.remote.url}: sync needs the drive. Use url: switchboard.drives.<slug>.url, or url: { $output: { host: \"switchboard\", path: [\"drives\", \"<slug>\", \"url\"] } }.`,\n });\n });\n\n const nameOf = (base: string) => byBase.get(base) ?? base;\n for (const [slug, name] of Object.entries(reactor.placement?.drives ?? {})) {\n const at = [\"placement\", \"drives\", slug];\n const on = [...(linked.get(slug) ?? [])];\n // Two drives answer to the key, whichever backend it names.\n if (on.length > 0 && kept.has(slug)) {\n ctx.addIssue({\n code: \"custom\",\n path: at,\n message: `Drive \"${slug}\" is both this reactor's own drive and on ${on.map(nameOf).join(\" and \")}. Rename one, or link only one.`,\n });\n continue;\n }\n if (on.length > 1) {\n ctx.addIssue({\n code: \"custom\",\n path: at,\n message: `Drive \"${slug}\" is on both ${on.map(nameOf).join(\" and \")}. Rename one, or link only one.`,\n });\n continue;\n }\n const base = baseOf.get(name);\n if (base === undefined) continue;\n if (on.length === 0) {\n // A key that names no drive here (a hashed home drive) is not checked.\n if (!kept.has(slug)) continue;\n ctx.addIssue({\n code: \"custom\",\n path: at,\n message: `placement.drives.${slug} opens drive \"${slug}\" on \"${name}\", but this reactor keeps that drive itself. Only a drive on a switchboard can open there without a copy.`,\n });\n continue;\n }\n if (on[0] === base) continue;\n ctx.addIssue({\n code: \"custom\",\n path: at,\n message: `placement.drives.${slug} opens drive \"${slug}\" on \"${name}\" (${base}), but the drive is on ${on[0]}. Place it on the backend for that switchboard.`,\n });\n }\n}\n\n/** `remote` keys that tune a connection, so only a remote backend has them. */\nconst REMOTE_ONLY_KEYS = [\"requestTimeoutMs\", \"breaker\", \"realtime\"] as const;\n\n/**\n * Builds the host schema set. \"allow\" (declared form) accepts `T | Token` in\n * every token-able field; \"forbid\" (resolved form) accepts `T` only.\n */\nfunction buildHostSchemas(tokenField: FieldWrappers) {\n const resolved = tokenField === FORBID_TOKENS;\n const reactorBackendSchema = z\n .strictObject({\n kind: reactorBackendKindSchema,\n storage: z\n .strictObject({\n kind: z.enum([\"idb\", \"memory\", \"path\", \"postgres\"]),\n /** `\"${userData}/…\"` sugar or `{ $env: \"NAME\" }`. */\n dataDir: tokenField.env(z.string()).optional(),\n url: z.string().optional(),\n })\n .optional(),\n readModel: z.strictObject({ url: z.string().optional() }).optional(),\n packages: z\n .strictObject({\n cdnUrl: z.string().optional(),\n specs: z.array(z.string()).optional(),\n /** on-demand model resolution (was DYNAMIC_MODEL_LOADING). */\n dynamic: z.boolean().optional(),\n })\n .optional(),\n // A switchboard drive address, `<base>/d/<slug>`: typically a\n // producer's `drives.<slug>.url` output token. The backend is the\n // switchboard at `<base>`. `${origin}/d/<slug>` when the member's own\n // server proxies the switchboard (the browser then calls its page\n // origin; see `runner.proxy` on the connect runner).\n remote: z\n .strictObject({\n url: tokenField.any(originOrUrlSchema),\n /** Give up on one request to this switchboard after this long. Default 30_000. */\n requestTimeoutMs: z.number().int().positive().optional(),\n /** After `failures` failed requests in a row, send nothing for\n * `openMs`. Default { failures: 3, openMs: 30_000 }. `false`:\n * never stop trying. */\n breaker: z\n .union([\n z.literal(false),\n z.strictObject({\n failures: z.number().int().min(1).optional(),\n openMs: z.number().int().nonnegative().optional(),\n }),\n ])\n .optional(),\n /** Live updates over a socket (the router's GraphQL\n * subscriptions, not drive sync). Default true. */\n realtime: z.boolean().optional(),\n })\n .optional(),\n })\n // Two PGlite instances on one data dir corrupt it: the reactor store\n // (storage.dataDir) and the read-model store (readModel.url) must differ.\n // Postgres is exempt: one database legitimately serves both stores.\n .superRefine((backend, ctx) => {\n // 2.1 \"a remote backend needs url\": `remote` is optional for the\n // in-process/worker kinds, but a remote backend attaches by URL only.\n if (backend.kind === \"remote\" && !backend.remote) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"remote\", \"url\"],\n message: `a \"remote\" backend needs remote.url, a switchboard drive address: ${useDriveUrl()}.`,\n });\n }\n if (backend.kind !== \"remote\" && backend.remote) {\n for (const key of REMOTE_ONLY_KEYS) {\n if (backend.remote[key] === undefined) continue;\n ctx.addIssue({\n code: \"custom\",\n path: [\"remote\", key],\n message: `remote.${key} applies only to a \"remote\" backend; this one is \"${backend.kind}\".`,\n });\n }\n }\n const url: unknown = backend.remote?.url;\n const graphqlRef = resolved ? undefined : endpointsGraphqlRef(url);\n if (graphqlRef) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"remote\", \"url\"],\n message: `remote.url reads ${graphqlRef.host}'s endpoints.graphql; it must be a switchboard drive address (<switchboard>/d/<slug>): sync needs the drive. Use ${useDriveUrl(graphqlRef.host, graphqlRef.member)}.`,\n });\n }\n if (resolved && typeof url === \"string\" && !switchboardOfDrive(url)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"remote\", \"url\"],\n message: `remote.url must be a switchboard drive address (<switchboard>/d/<slug>), not ${url}: sync needs the drive. Use ${useDriveUrl()}.`,\n });\n }\n const store = backend.storage;\n const storeDir = store?.kind === \"path\" ? store.dataDir : undefined;\n const readModel = backend.readModel?.url;\n // In the declared form dataDir may still be a `$env` token: compare\n // only resolved strings (resolved validation re-runs this check).\n if (\n typeof storeDir === \"string\" &&\n readModel &&\n samePath(storeDir, readModel)\n ) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"readModel\", \"url\"],\n message:\n `readModel.url must not be the reactor's storage dir (${readModel}): ` +\n \"two PGlite instances on one data dir corrupt it. Omit readModel.url \" +\n \"to get the classic <root>/.ph/read-storage next to the reactor store.\",\n });\n }\n });\n\n const reactorSchema = z\n .strictObject({\n backends: z.record(z.string(), reactorBackendSchema).optional(),\n placement: z\n .strictObject({\n primary: z.string().optional(),\n /** Declared drive slug → backend name. A local backend keeps a\n * synced copy; the drive's own remote backend opens it there with\n * no copy. An unlisted drive keeps a synced copy. */\n drives: z.record(z.string().min(1), z.string().min(1)).optional(),\n /** The backend new drives (and documents outside a drive) are\n * created on. A switchboard keeps no copy in this browser.\n * Default: the browser reactor, else the only switchboard. */\n newDrives: z.string().min(1).optional(),\n })\n .optional(),\n router: z\n .strictObject({\n /** Wait this long for a reactor to say whether it holds a\n * document. 0: no bound. Default 3_000. */\n probeTimeoutMs: z.number().int().nonnegative().optional(),\n /** Look again after this long for a document found on a later\n * backend. Default 30_000. */\n provisionalRouteMs: z.number().int().nonnegative().optional(),\n })\n .optional(),\n protocol: reactorProtocolSchema.optional(),\n /** DEPRECATED (dies in R2): workflows become a listed plugin. */\n workflows: z.boolean().optional(),\n // R1 core keys: identity/signing and storage namespace.\n renown: z\n .strictObject({\n url: z.string().optional(),\n networkId: z.string().optional(),\n chainId: z.number().int().optional(),\n })\n .optional(),\n namespace: z.string().min(1).optional(),\n // Core-declared, seeded by the host runtime. Token-able as a whole\n // (3.3): a `$map` over a producer's `drives` output (or an `$output` of\n // an array of declarations) renders the list at resolve time.\n drives: tokenField\n .any(z.array(buildDriveDeclarationSchema(tokenField.any)))\n .optional(),\n })\n .superRefine((reactor, ctx) => {\n const backends = reactor.backends ?? {};\n for (const [slug, name] of Object.entries(\n reactor.placement?.drives ?? {},\n )) {\n if (Object.hasOwn(backends, name)) continue;\n ctx.addIssue({\n code: \"custom\",\n path: [\"placement\", \"drives\", slug],\n message: `placement.drives.${slug} names backend \"${name}\", which is not in backends (${Object.keys(backends).join(\", \") || \"none\"}).`,\n });\n }\n const newDrives = reactor.placement?.newDrives;\n if (newDrives !== undefined && !Object.hasOwn(backends, newDrives)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"placement\", \"newDrives\"],\n message: `placement.newDrives names backend \"${newDrives}\", which is not in backends (${Object.keys(backends).join(\", \") || \"none\"}).`,\n });\n }\n if (resolved) refineResolvedReactor(reactor, ctx);\n });\n\n /** Common runner options; runner modules extend it with their own. */\n const runnerBaseSchema = z.looseObject({\n module: z.string().min(1),\n defaultVerb: z.string().min(1).optional(),\n port: z.number().int().positive().optional(),\n /** Bind address; each runner documents its default. */\n host: z.string().min(1).optional(),\n /** THE COMPOSITION: plugin entries; presence is activation. */\n plugins: z.array(pluginEntrySchema).optional(),\n });\n\n /** A compound member wrapper. Sections are FULL STATEMENTS except `runner`,\n * which key-merges over the member's own. Plugins live in `runner.plugins`\n * (as on a standalone host); there is no wrapper-level `plugins`. */\n const childWrapperSchema = z.strictObject({\n host: z.string().min(1),\n // 0 passes here; the member runner's own schema decides whether it may.\n runner: runnerBaseSchema\n .partial()\n .extend({ port: z.number().int().min(0).max(65535).optional() })\n .optional(),\n config: z.looseObject({}).optional(),\n reactor: reactorSchema.optional(),\n });\n\n const childrenSchema = z.record(z.string(), childWrapperSchema);\n\n const reactorHostSchema = z.strictObject({\n name: hostNameSchema,\n runner: runnerBaseSchema,\n config: z.looseObject({}).optional(),\n profile: profileSchema.optional(),\n reactor: reactorSchema.optional(),\n });\n\n const compoundHostSchema = z.strictObject({\n name: hostNameSchema,\n runner: runnerBaseSchema,\n children: childrenSchema,\n config: z.looseObject({}).optional(),\n profile: profileSchema.optional(),\n });\n\n return {\n reactorBackendSchema,\n reactorSchema,\n runnerBaseSchema,\n childWrapperSchema,\n childrenSchema,\n reactorHostSchema,\n compoundHostSchema,\n /** This set's field wrapper, for a runner's OWN token-able fields inside\n * `defineHostSchemas`: declared, `T | Token` in and `T` out; resolved,\n * `T` only. Both modes share one static type. */\n tokenable: tokenField.any,\n /** As `tokenable`, but the only token accepted is `$env`. */\n envTokenable: tokenField.env,\n };\n}\n\nexport type HostSchemas = ReturnType<typeof buildHostSchemas>;\n\n/** The host schema set in declared (\"allow\": token-able fields take tokens)\n * or resolved (\"forbid\") form. */\nexport function makeHostSchemas(options: { tokens: TokenMode }): HostSchemas {\n return buildHostSchemas(\n options.tokens === \"allow\" ? ALLOW_TOKENS : FORBID_TOKENS,\n );\n}\n\nexport type PlacementKeyIssue = {\n path: (string | number)[];\n message: string;\n};\n\n/** The issues a host-level refinement raises, outside a zod parse. */\nfunction collectIssues(\n host: unknown,\n refine: (host: DeclaredReactorHost, ctx: z.RefinementCtx) => void,\n): PlacementKeyIssue[] {\n if (typeof host !== \"object\" || host === null || !(\"reactor\" in host)) {\n return [];\n }\n const issues: PlacementKeyIssue[] = [];\n const ctx = {\n addIssue: (issue: { path?: PropertyKey[]; message?: string }) => {\n issues.push({\n path: (issue.path ?? []).filter(\n (part): part is string | number => typeof part !== \"symbol\",\n ),\n message: issue.message ?? \"\",\n });\n },\n } as unknown as z.RefinementCtx;\n refine(host as DeclaredReactorHost, ctx);\n return issues;\n}\n\n/** withPlacementKeys' check, for a merged declared host parsed some other way. */\nexport function placementKeyIssues(host: unknown): PlacementKeyIssue[] {\n return collectIssues(host, refineDeclaredPlacementKeys);\n}\n\nexport const CONNECT_PRIMARY_MESSAGE =\n \"Connect doesn't use placement.primary. To choose where new drives go, use placement.newDrives.\";\n\n/**\n * A Connect host's placement rules, in either form. The router's primary is\n * the browser reactor, else the `newDrives` switchboard, else the only one,\n * so `placement.primary` means nothing here, and a Connect with several\n * switchboards and no browser reactor must say where new drives go. Apply it\n * last to the Connect runner's schema: `.superRefine(refineConnectReactor)`.\n */\nexport function refineConnectReactor(\n host: { reactor?: unknown },\n ctx: z.RefinementCtx,\n): void {\n const reactor = (host as DeclaredReactorHost).reactor;\n if (!reactor) return;\n if (reactor.placement?.primary !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"reactor\", \"placement\", \"primary\"],\n message: CONNECT_PRIMARY_MESSAGE,\n });\n }\n const backends = Object.entries(reactor.backends ?? {});\n const remotes = backends\n .filter(([, backend]) => backend.kind === \"remote\")\n .map(([name]) => name);\n if (\n remotes.length > 1 &&\n remotes.length === backends.length &&\n reactor.placement?.newDrives === undefined\n ) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"reactor\", \"placement\", \"newDrives\"],\n message: `This Connect keeps no reactor in the browser and links ${remotes.length} switchboards (${remotes.join(\", \")}). Set placement.newDrives to the one new drives are created on.`,\n });\n }\n}\n\n/** refineConnectReactor's check, for a Connect host parsed some other way. */\nexport function connectReactorIssues(host: unknown): PlacementKeyIssue[] {\n return collectIssues(host, refineConnectReactor);\n}\n\n/** Adds the host-level placement key check to a runner's declared schema. */\nfunction withPlacementKeys<T>(schema: T): T {\n if (!(schema instanceof z.ZodType)) return schema;\n return schema.superRefine((host, ctx) => {\n if (typeof host === \"object\" && host !== null && \"reactor\" in host) {\n refineDeclaredPlacementKeys(host as DeclaredReactorHost, ctx);\n }\n }) as T;\n}\n\n/**\n * One runner definition, two schemas (3.5): `build` runs over the DECLARED\n * set (tokens allowed; its z.input types host files) and the RESOLVED set\n * (no tokens; `validateHost` checks it before the verb). Export both, type\n * the host as `z.input<typeof declaredHostSchema>`, refine last inside the\n * builder (zod can't extend a refined object), and wrap the runner's own\n * token-able fields with `s.tokenable` / `s.envTokenable`.\n */\nexport function defineHostSchemas<T>(build: (schemas: HostSchemas) => T): {\n declaredHostSchema: T;\n hostSchema: T;\n} {\n return {\n declaredHostSchema: withPlacementKeys(build(declaredSchemas)),\n hostSchema: build(resolvedSchemas),\n };\n}\n\nconst declaredSchemas = makeHostSchemas({ tokens: \"allow\" });\nconst resolvedSchemas = makeHostSchemas({ tokens: \"forbid\" });\n\n/* The exported base blocks are the RESOLVED form (what verbs receive). The\n * declared forms are `declaredHostSchemas` / `defineHostSchemas`. */\nexport const declaredHostSchemas: HostSchemas = declaredSchemas;\nexport const reactorBackendSchema = resolvedSchemas.reactorBackendSchema;\nexport const reactorSchema = resolvedSchemas.reactorSchema;\nexport const runnerBaseSchema = resolvedSchemas.runnerBaseSchema;\nexport const childWrapperSchema = resolvedSchemas.childWrapperSchema;\nexport const childrenSchema = resolvedSchemas.childrenSchema;\nexport const reactorHostSchema = resolvedSchemas.reactorHostSchema;\nexport const compoundHostSchema = resolvedSchemas.compoundHostSchema;\n\n/** The generic compound runner's host: the base with its wiring config. */\nconst genericCompound = defineHostSchemas((s) =>\n s.compoundHostSchema\n .extend({ config: compoundWiringSchema.optional() })\n .superRefine(refineStartOrder),\n);\nexport const genericCompoundHostSchema = genericCompound.hostSchema;\nexport const declaredGenericCompoundHostSchema =\n genericCompound.declaredHostSchema;\n\n/* -------------------------------------------------------------------- types */\n\nexport type Profile = z.infer<typeof profileSchema>;\nexport type ReactorProtocol = z.infer<typeof reactorProtocolSchema>;\nexport type ReactorBackend = z.infer<typeof reactorBackendSchema>;\nexport type ReactorBackendKind = ReactorBackend[\"kind\"];\nexport type ReactorStorageConfig = NonNullable<ReactorBackend[\"storage\"]>;\nexport type ReactorPackageConfig = NonNullable<ReactorBackend[\"packages\"]>;\nexport type ReactorRemoteConfig = NonNullable<ReactorBackend[\"remote\"]>;\nexport type ReactorConfig = z.infer<typeof reactorSchema>;\nexport type RunnerBase = z.infer<typeof runnerBaseSchema>;\nexport type ChildWrapper = z.infer<typeof childWrapperSchema>;\nexport type CompoundWiring = z.infer<typeof compoundWiringSchema>;\n\n/** What a host.js author writes (z.input), per runner kind. The `never`\n * sides make reactor XOR children a type error. */\nexport type ReactorHostInput = z.input<\n typeof declaredSchemas.reactorHostSchema\n> & {\n children?: never;\n};\nexport type CompoundHostInput = z.input<\n typeof declaredSchemas.compoundHostSchema\n> & {\n reactor?: never;\n};\nexport type HostDefinition = ReactorHostInput | CompoundHostInput;\n\n/** What a verb receives (z.output) from the base schemas. */\nexport type ReactorHost = z.output<typeof reactorHostSchema>;\nexport type CompoundHost = z.output<typeof compoundHostSchema>;\n\n/* --------------------------------------------------------------- JSON Schema */\n\nconst SCHEMA_BASE = \"https://powerhouse.inc/schemas\";\n\n/** One host schema as an editor JSON Schema with a stable `$id` — the\n * per-runner emission helper (runner packages emit their own hostSchema). */\nexport function emitHostJsonSchema(\n name: string,\n schema: z.ZodType,\n): Record<string, unknown> {\n return {\n $id: `${SCHEMA_BASE}/${name}.schema.json`,\n ...z.toJSONSchema(schema, { io: \"input\" }),\n };\n}\n\n/** The emitted-schema set, keyed by published filename. Pure — the\n * emit-schemas script writes these and the drift test re-derives them. */\nexport function emittedHostSchemas(): Record<string, unknown> {\n return {\n // Editor schemas describe what authors write: the declared form.\n \"host-reactor.schema.json\": emitHostJsonSchema(\n \"host-reactor\",\n declaredSchemas.reactorHostSchema,\n ),\n \"host-compound.schema.json\": emitHostJsonSchema(\n \"host-compound\",\n declaredSchemas.compoundHostSchema,\n ),\n };\n}\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 { 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","/**\n * Pure built-in `$env` substitution: the `\"${userData}\"` / `\"${projectRoot}\"`\n * string sugar, deep-applied to a JSON-shaped value. No node imports, so it\n * ships in `./schema`; the node default for userData is placeholders.ts.\n */\n\nexport interface BuiltinEnv {\n userData?: string;\n projectRoot?: string;\n}\n\n/** The always-resolvable `$env` names (also the `\"${name}\"` sugar). */\nexport const BUILTIN_ENV_NAMES: readonly (keyof BuiltinEnv)[] = [\n \"userData\",\n \"projectRoot\",\n];\n\nexport function isBuiltinEnvName(name: string): name is keyof BuiltinEnv {\n return (BUILTIN_ENV_NAMES as readonly string[]).includes(name);\n}\n\nconst BUILTIN = new RegExp(`\\\\$\\\\{(${BUILTIN_ENV_NAMES.join(\"|\")})\\\\}`, \"g\");\n\nfunction substitute(text: string, env: BuiltinEnv): string {\n return text.replace(\n BUILTIN,\n (match, name: keyof BuiltinEnv) => env[name] ?? match,\n );\n}\n\n/** Deep-substitute the built-ins that `env` provides in every string; an\n * absent built-in is left as written. The input is never mutated. */\nexport function substituteBuiltinEnv<T>(value: T, env: BuiltinEnv): T {\n return substituteValue(value, env) as T;\n}\n\nfunction substituteValue(value: unknown, env: BuiltinEnv): unknown {\n if (typeof value === \"string\") return substitute(value, env);\n if (Array.isArray(value)) return value.map((v) => substituteValue(v, env));\n if (value !== null && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n out[k] = substituteValue(v, env);\n }\n return out;\n }\n return value;\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\n/**\n * What a one-shot verb (build) gets for a `$map`: no outputs exist there, so\n * every map in `declared` renders no elements (`[]`, or `{}` with into:\n * \"record\") at its path in `host`, the declared-form parse of `declared`.\n * Other tokens stay, as they do in token-able fields.\n */\nexport function emptyMaps<T>(host: T, declared: unknown): T {\n const maps = collectTokenSites(declared).filter(\n (site) =>\n site.key === \"$map\" &&\n site.scopes.length === 0 &&\n site.position !== \"concat\",\n );\n if (maps.length === 0) return host;\n const out: unknown = cloneWithProvenance(host);\n for (const { path, token } of maps) {\n const operand = token.$map;\n const record = isPlainObject(operand) && operand.into === \"record\";\n setAt(out, path, record ? {} : [], false);\n }\n return out as T;\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 { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { runnerKindSchema, type RunnerKind } from \"./host-schemas.js\";\nimport {\n checkOutputPaths,\n checkTokenSites,\n type DeclaredIssue,\n type OutputRef,\n type OutputsSchemaLookup,\n} from \"./resolve/declared.js\";\nimport { findRemovedForms } from \"./resolve/removed-forms.js\";\nimport { describeMapElements } from \"./resolve/resolve.js\";\nimport { formatPath, unwrapEscapes } from \"./resolve/walk.js\";\nimport { findToken, tokenKeyOf, type TokenMode } from \"./tokens.js\";\n\n/**\n * Resolves a host's `runner.module` specifier from the PROJECT's dependency\n * tree (not ph-cli's), imports it, and checks the runner-module contract:\n * `{ run, hostSchema, kind, outputsSchema?, verbs?, ...optionalVerbs }`.\n */\n\nexport class RunnerError extends Error {\n constructor(message: string, hint?: string) {\n super(hint ? `${message}\\n Hint: ${hint}` : message);\n this.name = \"RunnerError\";\n }\n}\n\nexport interface RunnerContext {\n projectRoot: string;\n /** The verb this runner runs at. For a compound member it is the member's\n * OWN effective verb (e.g. \"serve\" under a compound at \"run\"). */\n verb: string;\n env: Record<string, string | undefined>;\n /** Set when this runner runs as a compound member: the compound's host\n * name and verb. */\n parent?: { host: string; verb: string };\n /** This invocation's arguments for this runner: what followed\n * `ph run <host> [verb]`, checked against the runner's `argsSchema`. They\n * win over the host file. A compound member gets its own share. */\n argv?: readonly string[];\n}\n\n/** A verb receives the PARSED host (its runner's hostSchema output), so\n * schema defaults and transforms reach it. */\nexport type RunnerVerb<O = unknown> = (\n host: O,\n ctx: RunnerContext,\n) => Promise<unknown>;\n\nexport interface HostSchemaIssue {\n path: PropertyKey[];\n message: string;\n code?: string;\n}\n\n/** zod-shaped structurally, so a runner may bring its own zod instance. */\nexport interface HostSchemaLike<O = unknown> {\n safeParse(\n host: unknown,\n ):\n | { success: true; data: O }\n | { success: false; error: { issues: readonly HostSchemaIssue[] } };\n}\n\n/** Whether a value is zod-shaped (has a `safeParse` function): a runner's\n * `outputsSchema`, a plugin's config schema. */\nexport function isSchemaLike(value: unknown): value is HostSchemaLike {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"safeParse\" in value &&\n typeof value.safeParse === \"function\"\n );\n}\n\n/** The Connect runner's specifier: compounds forward `cspRegistrySync` to\n * it, and `--explain` prints its dead-config warnings. */\nexport const CONNECT_RUNNER = \"@powerhousedao/ph-cli/runners/connect\";\n\nexport interface RunnerModule<O = unknown> {\n run: RunnerVerb<O>;\n /** The RESOLVED host schema: no tokens; checked right before the verb. */\n hostSchema: HostSchemaLike<O>;\n /** The DECLARED host schema (token-able fields accept tokens), from the\n * same definition (`defineHostSchemas`). Absent: declared validation\n * checks the tokens only, and shape errors surface at resolved\n * validation. */\n declaredHostSchema?: HostSchemaLike;\n kind: RunnerKind;\n /** What a started host produces (G3); `$output` paths are checked\n * against it. Absent: the runner produces no outputs. */\n outputsSchema?: unknown;\n /** The verb names, when the module exports functions that are not verbs\n * (helpers). Absent: every exported function is a verb. */\n verbs?: readonly string[];\n /** The arguments the runner accepts after `ph run <host> [verb]`\n * (`RunnerArgsSchema`). Absent: it accepts none, and any argument fails. */\n argsSchema?: unknown;\n /** What the verb would refuse at boot, given the parsed host and an\n * environment (`ph host check`). Starts nothing. */\n checkBoot?: (\n host: O,\n ctx: BootCheckContext,\n ) => readonly BootIssue[] | Promise<readonly BootIssue[]>;\n [key: string]: unknown;\n}\n\nexport interface BootCheckContext {\n projectRoot: string;\n /** The verb the host would run at (a compound member's own verb). */\n verb: string;\n /** The environment the verb would see; never `process.env` implicitly. */\n env: Readonly<Record<string, string | undefined>>;\n /** The host file, for messages (`hosts/switchboard/host.js`). */\n file: string;\n}\n\nexport interface BootIssue {\n path?: string;\n message: string;\n hint?: string;\n}\n\n/** Exports that are part of the contract but are not verbs. */\nconst NON_VERB_EXPORTS = new Set([\n \"hostSchema\",\n \"declaredHostSchema\",\n \"outputsSchema\",\n \"verbs\",\n \"argsSchema\",\n \"kind\",\n \"checkBoot\",\n \"default\",\n]);\n\n/** ph-cli's runners are ph-run's plus the verbs that build. A packaged app has\n * only ph-run, and its host files, generated against ph-cli's, name ph-cli's. */\nexport function runnerFallback(specifier: string): string | undefined {\n const name = /^@powerhousedao\\/ph-cli\\/(runners\\/.+)$/.exec(specifier)?.[1];\n return name ? `@powerhousedao/ph-run/${name}` : undefined;\n}\n\nexport async function resolveRunnerModule(\n projectRoot: string,\n specifier: string,\n): Promise<RunnerModule> {\n const projectRequire = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n const resolveFirst = (candidates: string[]): string => {\n const [first, ...rest] = candidates;\n try {\n return projectRequire.resolve(first);\n } catch (error) {\n if (rest.length === 0) throw error;\n return resolveFirst(rest);\n }\n };\n let resolved: string;\n try {\n const fallback = runnerFallback(specifier);\n resolved = resolveFirst(fallback ? [specifier, fallback] : [specifier]);\n } catch {\n throw new RunnerError(\n `Cannot resolve runner module \"${specifier}\" from ${projectRoot}.`,\n \"The runner must be a dependency of the project (install it, then retry).\",\n );\n }\n\n const module = (await import(pathToFileURL(resolved).href)) as Record<\n string,\n unknown\n >;\n\n if (typeof module.run !== \"function\") {\n throw new RunnerError(\n `Runner \"${specifier}\" does not export a \\`run\\` function (required verb).`,\n );\n }\n const hostSchema = module.hostSchema as HostSchemaLike | undefined;\n if (!hostSchema || typeof hostSchema.safeParse !== \"function\") {\n throw new RunnerError(\n `Runner \"${specifier}\" does not export a \\`hostSchema\\` — runners validate their own host shape.`,\n );\n }\n const declared = module.declaredHostSchema as HostSchemaLike | undefined;\n if (declared !== undefined && typeof declared.safeParse !== \"function\") {\n throw new RunnerError(\n `Runner \"${specifier}\" exports a \\`declaredHostSchema\\` without safeParse.`,\n );\n }\n if (\n module.checkBoot !== undefined &&\n typeof module.checkBoot !== \"function\"\n ) {\n throw new RunnerError(\n `Runner \"${specifier}\" exports a \\`checkBoot\\` that is not a function.`,\n );\n }\n const verbs = module.verbs;\n if (\n verbs !== undefined &&\n (!Array.isArray(verbs) ||\n !verbs.every(\n (verb: unknown) =>\n typeof verb === \"string\" && typeof module[verb] === \"function\",\n ))\n ) {\n throw new RunnerError(\n `Runner \"${specifier}\" exports \\`verbs\\` ${JSON.stringify(verbs)}, which must list names of exported functions.`,\n );\n }\n if (!runnerKindSchema.safeParse(module.kind).success) {\n throw new RunnerError(\n `Runner \"${specifier}\" does not export a valid \\`kind\\` (got ${JSON.stringify(module.kind)}; expected \"reactor\" | \"compound\").`,\n );\n }\n return module as unknown as RunnerModule;\n}\n\n/** Verbs that produce something and start nothing (`build`): no outputs, no\n * record, no lock — and no token resolution, since what they read (output\n * dirs, packages) never comes from another host's outputs. Their verb gets\n * the declared host (tokens may remain in token-able fields; a `$map` is\n * the empty collection, see `emptyMaps`). */\nexport const ONE_SHOT_VERBS: ReadonlySet<string> = new Set([\"build\"]);\n\n/** Verbs that work on a host's stores and start nothing (`migrate`,\n * `migrate-status`, `reset`). Their host is resolved as for `run`, so they\n * address the stores `run` opens; they take no lock and return nothing, so\n * no record is written. A compound does not forward them. */\nexport const STORE_VERBS: ReadonlySet<string> = new Set([\n \"migrate\",\n \"migrate-status\",\n \"reset\",\n]);\n\nexport function listVerbs<O>(runner: RunnerModule<O>): string[] {\n if (runner.verbs) {\n return runner.verbs\n .filter((name) => typeof runner[name] === \"function\")\n .toSorted();\n }\n return Object.entries(runner)\n .filter(\n ([name, value]) =>\n typeof value === \"function\" && !NON_VERB_EXPORTS.has(name),\n )\n .map(([name]) => name)\n .sort();\n}\n\nexport function getVerb<O>(\n runner: RunnerModule<O>,\n specifier: string,\n verb: string,\n): RunnerVerb<O> {\n const candidate = runner[verb];\n if (typeof candidate !== \"function\" || !listVerbs(runner).includes(verb)) {\n throw new RunnerError(\n `Runner \"${specifier}\" does not support the verb \"${verb}\". Supported verbs: ${listVerbs(\n runner,\n ).join(\", \")}.`,\n );\n }\n return candidate as RunnerVerb<O>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** A contract violation found while validating a host, without the file\n * prefix the throwing validators add. */\nexport interface RunnerIssue {\n path: string;\n message: string;\n hint?: string;\n}\n\n/** reactor XOR children, decided by the runner's declared `kind`. */\nexport function kindShapeIssues(\n kind: RunnerKind,\n specifier: string,\n host: Record<string, unknown>,\n): RunnerIssue[] {\n if (kind === \"reactor\" && host.children !== undefined) {\n return [\n {\n path: \"children\",\n message: `\"${specifier}\" is a reactor runner, so the host must not declare \\`children\\`.`,\n hint: \"`children` belongs to compound hosts; a reactor host configures its own `reactor` block.\",\n },\n ];\n }\n if (kind === \"compound\" && host.reactor !== undefined) {\n return [\n {\n path: \"reactor\",\n message: `\"${specifier}\" is a compound runner, so the host must not declare \\`reactor\\`.`,\n hint: \"A compound's reactors are its members': configure them in the member host or a wrapper's `reactor` override.\",\n },\n ];\n }\n return [];\n}\n\nfunction assertKindShape(\n kind: RunnerKind,\n specifier: string,\n host: Record<string, unknown>,\n file: string,\n): void {\n const issue = kindShapeIssues(kind, specifier, host).at(0);\n if (issue) throw new RunnerError(`${file}: ${issue.message}`, issue.hint);\n}\n\n/** `runner.defaultVerb` and every plugin entry's `verbs` must name verbs\n * this runner exports. */\nexport function knownVerbIssues<O>(\n runner: RunnerModule<O>,\n specifier: string,\n host: Record<string, unknown>,\n): RunnerIssue[] {\n const options = host.runner;\n if (!isRecord(options)) return [];\n const verbs = listVerbs(runner);\n const unknownVerb = (verb: unknown): verb is string =>\n typeof verb === \"string\" && !verbs.includes(verb);\n const issues: RunnerIssue[] = [];\n if (unknownVerb(options.defaultVerb)) {\n issues.push({\n path: \"runner.defaultVerb\",\n message: `runner.defaultVerb \"${options.defaultVerb}\" is not a verb of \"${specifier}\". Supported verbs: ${verbs.join(\", \")}.`,\n });\n }\n const plugins: unknown[] = Array.isArray(options.plugins)\n ? options.plugins\n : [];\n plugins.forEach((entry, index) => {\n if (!isRecord(entry) || !Array.isArray(entry.verbs)) return;\n const scoped: unknown[] = entry.verbs;\n for (const bad of scoped.filter(unknownVerb)) {\n issues.push({\n path: `runner.plugins[${index}].verbs`,\n message: `plugin \"${String(entry.module)}\" is scoped to verb \"${bad}\", which \"${specifier}\" does not export. Supported verbs: ${verbs.join(\", \")}.`,\n });\n }\n });\n return issues;\n}\n\nfunction formatIssues(issues: readonly DeclaredIssue[]): string {\n return issues.map((i) => ` - ${i.path}: ${i.message}`).join(\"\\n\");\n}\n\nfunction valueAt(host: unknown, path: readonly PropertyKey[]): unknown {\n let current = host;\n for (const key of path) {\n if (Array.isArray(current) && typeof key === \"number\") {\n current = current[key];\n } else if (isRecord(current) && typeof key === \"string\") {\n current = current[key];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\nexport interface ValidateHostOptions {\n /** \"forbid\" (default): the resolved form, checked with `hostSchema`; no\n * token may remain. \"allow\": the declared form, checked with\n * `declaredHostSchema` (else `hostSchema`) — what a COMPOUND runner's verb\n * receives, since its members resolve their own tokens. */\n tokens?: TokenMode;\n}\n\n/**\n * Resolved validation (pipeline step 6): validate a RESOLVED host against\n * its runner's `hostSchema` and return the PARSED host (what the verb\n * receives). Run `resolveHostOutputs` first; a token still present fails\n * with its path.\n */\nexport function validateHost<O>(\n runner: RunnerModule<O>,\n specifier: string,\n host: unknown,\n file: string,\n options: ValidateHostOptions = {},\n): O {\n const schema =\n options.tokens === \"allow\"\n ? (runner.declaredHostSchema ?? runner.hostSchema)\n : runner.hostSchema;\n // Same definition (defineHostSchemas), so the declared parse has the\n // verb's shape; only token-able fields may still hold tokens.\n return parseHost(\n runner,\n schema as HostSchemaLike<O>,\n specifier,\n host,\n file,\n options,\n );\n}\n\nexport interface SchemaIssue extends RunnerIssue {\n /** The line `validateHost` prints: zod's dotted path (other runners' tests\n * match on it), then the message. */\n printed: string;\n}\n\nexport interface HostSchemaIssues<O> {\n /** Kind shape, an unresolved token (forbid mode) and unknown verbs, in\n * the order the throwing validator checks them. */\n issues: RunnerIssue[];\n /** The schema's own issues; absent when the host parsed. */\n schemaIssues?: SchemaIssue[];\n data?: O;\n}\n\n/** What `validateHost` checks, as data: nothing throws. */\nexport function hostSchemaIssues<O>(\n runner: RunnerModule<O>,\n schema: HostSchemaLike<O>,\n specifier: string,\n host: unknown,\n options: ValidateHostOptions = {},\n): HostSchemaIssues<O> {\n const issues: RunnerIssue[] = [];\n if (isRecord(host)) {\n issues.push(...kindShapeIssues(runner.kind, specifier, host));\n if (options.tokens !== \"allow\") {\n const token = findToken(host);\n if (token) {\n issues.push({\n path: token.path,\n message: `\\`${token.path}\\` is an unresolved output token (${token.key}).`,\n hint: \"Resolve the host (resolveHostOutputs) before validating it for a verb; `ph run` does this.\",\n });\n }\n }\n issues.push(...knownVerbIssues(runner, specifier, host));\n }\n // `$$` escapes protect literal `$`-keyed objects through the token walk;\n // the schema (and the verb) see the literal.\n const result = schema.safeParse(unwrapEscapes(host));\n if (result.success) return { issues, data: result.data };\n const schemaIssues = result.error.issues.map((issue): SchemaIssue => {\n const element = describeMapElements(host, issue.path);\n const dotted =\n (issue.path.map(String).join(\".\") || \"<root>\") +\n (element ? ` (${element})` : \"\");\n // A token in a field that does not take one: say so, rather than\n // the field type's own \"expected string\". A refinement's own message\n // about a token stands.\n const message =\n issue.code !== \"custom\" && tokenKeyOf(valueAt(host, issue.path))\n ? \"this field does not take an output token (it is not token-able); spell the value literally.\"\n : issue.message;\n return {\n path: formatPath(\n issue.path.filter(\n (key): key is string | number =>\n typeof key === \"string\" || typeof key === \"number\",\n ),\n ),\n message: element ? `${message} (${element})` : message,\n printed: `${dotted}: ${message}`,\n };\n });\n return { issues, schemaIssues };\n}\n\nfunction parseHost<O>(\n runner: RunnerModule<O>,\n schema: HostSchemaLike<O>,\n specifier: string,\n host: unknown,\n file: string,\n options: ValidateHostOptions,\n): O {\n const checked = hostSchemaIssues(runner, schema, specifier, host, options);\n const first = checked.issues.at(0);\n if (first) throw new RunnerError(`${file}: ${first.message}`, first.hint);\n if (checked.schemaIssues) {\n const issues = checked.schemaIssues\n .map((issue) => ` - ${issue.printed}`)\n .join(\"\\n\");\n throw new RunnerError(\n `${file} failed validation against the hostSchema of \"${specifier}\":\\n${issues || \" (no details reported)\"}`,\n );\n }\n return checked.data as O;\n}\n\nexport interface DeclaredHostOptions {\n /** Producer lookup for `$output` path checks. Absent: paths are not\n * checked here (a compound checks its members' tokens per member). */\n outputsSchemaOf?: (ref: OutputRef) => OutputsSchemaLookup;\n}\n\n/**\n * Declared validation (pipeline step 3): the removed cross-host forms\n * (each error names its token form), token shapes and `$env` `optional`\n * placement, `$output` paths against the producers' `outputsSchema`s, then\n * the runner's `declaredHostSchema` (tokens allowed in token-able fields).\n * Reads no environment value and needs no producer running. Throws on the\n * first failing stage; resolve, then `validateHost`, before a verb runs.\n */\nexport function validateDeclaredHost(\n runner: RunnerModule,\n specifier: string,\n host: unknown,\n file: string,\n options: DeclaredHostOptions = {},\n): void {\n const removed = findRemovedForms(host);\n if (removed.length > 0) {\n throw new RunnerError(`${file}: removed form:\\n${formatIssues(removed)}`);\n }\n const issues = checkTokenSites(host);\n if (options.outputsSchemaOf) {\n issues.push(...checkOutputPaths(host, options.outputsSchemaOf));\n }\n if (issues.length > 0) {\n throw new RunnerError(\n `${file}: invalid output token:\\n${formatIssues(issues)}`,\n );\n }\n if (isRecord(host)) assertKindShape(runner.kind, specifier, host, file);\n if (!runner.declaredHostSchema) return;\n parseHost(runner, runner.declaredHostSchema, specifier, host, file, {\n tokens: \"allow\",\n });\n}\n","import { createHash } from \"node:crypto\";\nimport { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { z } from \"zod\";\nimport type { HostDefinition } from \"./host-schemas.js\";\nimport type { PluginEntryData } from \"./plugins.js\";\nimport { resolvePluginContributions } from \"./plugins-resolve.js\";\nimport { resolveRunnerModule } from \"./runner-resolver.js\";\n\n/**\n * Loads and pre-validates a `hosts/<name>/host.js` definition.\n *\n * A host file is a static PROJECTION of powerhouse.config.json: plain ESM,\n * default-exporting a data object. Three gates run before any runner sees it:\n * 1. import lint — the only legal imports are the project's\n * powerhouse.config.json, sibling `../<host>/host.js` files and sibling\n * generated `../<host>/outputs.js` token trees (host files are data, not\n * programs; `process.` is banned, environment values go through `$env`).\n * An imported outputs.js whose schema hash no longer matches its\n * producer fails here (\"run `ph generate hosts`\");\n * 2. static check — the exported object must survive a JSON round trip\n * (functions, undefined, class instances, Dates etc. are rejected,\n * reporting the offending path);\n * 3. shape pre-check — `name`, `runner.module`, and the reactor XOR children\n * rule. Full validation is the runner's `hostSchema` (phase 2).\n *\n * This module never exits the process — callers own error presentation.\n */\n\nconst HOST_FILE = \"host.js\";\nconst CONFIG_IMPORT_SUFFIX = \"powerhouse.config.json\";\n\nexport class HostLoadError extends Error {\n constructor(message: string, hint?: string) {\n super(hint ? `${message}\\n Hint: ${hint}` : message);\n this.name = \"HostLoadError\";\n }\n}\n\nexport type HostsFolderStatus =\n | { kind: \"absent\" }\n | { kind: \"empty\"; dir: string }\n | { kind: \"present\"; dir: string; hosts: string[] };\n\n/** A `hosts/` folder with no `<name>/host.js` inside is \"empty\" — the guard\n * state: callers warn loudly and fall back to legacy rather than activating\n * the new architecture off a stray `mkdir hosts`. */\nexport function probeHostsFolder(projectRoot: string): HostsFolderStatus {\n const dir = path.join(projectRoot, \"hosts\");\n if (!existsSync(dir) || !statSync(dir).isDirectory()) {\n return { kind: \"absent\" };\n }\n const hosts = readdirSync(dir, { withFileTypes: true })\n .filter(\n (entry) =>\n entry.isDirectory() &&\n existsSync(path.join(dir, entry.name, HOST_FILE)),\n )\n .map((entry) => entry.name)\n .sort();\n return hosts.length === 0\n ? { kind: \"empty\", dir }\n : { kind: \"present\", dir, hosts };\n}\n\n/** Sibling imports: `../<host>/host.js` — source material for derived\n * compositions (full-inclusion wrappers compute over them with plain JS) —\n * and `../<host>/outputs.js`, the generated `$output` token tree. */\nconst SIBLING_IMPORT = /^\\.\\.\\/([A-Za-z0-9_-]+)\\/(host\\.js|outputs\\.js)$/;\n\n/** The generated per-host token tree (`ph generate hosts`). */\nexport const OUTPUTS_FILE = \"outputs.js\";\nconst GENERATE_HINT =\n \"Run `ph generate hosts` to (re)generate hosts/<name>/outputs.js from the producer's runner outputsSchema and declared drives.\";\n\n/**\n * One pass over JS source that blanks every comment and, with\n * `literals: \"blank\"`, the CONTENTS of string literals and template-literal\n * text (quotes, backticks and `${`/`}` kept). A template's `${…}` holes are\n * code: they are scanned like the rest (strings, nested templates and braces\n * inside them included). Every newline survives, so line-anchored checks and\n * line numbers still match the original source. Regex literals are not\n * recognised (host files are data; a regex is not one).\n */\nfunction scanSource(source: string, literals: \"keep\" | \"blank\"): string {\n const blank = (text: string) => text.replace(/[^\\n]/g, \" \");\n const literal = (text: string) => (literals === \"blank\" ? blank(text) : text);\n let out = \"\";\n let i = 0;\n // One entry per open `${` hole: the depth of `{` opened inside it.\n const holes: number[] = [];\n /** Template text from `i` (just after a backtick or a hole's `}`) up to\n * and including its closing backtick, or up to and including the next\n * `${` (pushing a hole). */\n const templateText = (): void => {\n let j = i;\n while (j < source.length) {\n const ch = source[j];\n if (ch === \"\\\\\") {\n j += 2;\n continue;\n }\n if (ch === \"`\") break;\n if (ch === \"$\" && source[j + 1] === \"{\") break;\n j++;\n }\n out += literal(source.slice(i, Math.min(j, source.length)));\n if (j >= source.length) {\n i = source.length;\n } else if (source[j] === \"`\") {\n out += \"`\";\n i = j + 1;\n } else {\n out += \"${\";\n holes.push(0);\n i = j + 2;\n }\n };\n while (i < source.length) {\n const ch = source[i];\n const next = source[i + 1];\n if (ch === \"/\" && next === \"/\") {\n const end = source.indexOf(\"\\n\", i);\n const stop = end === -1 ? source.length : end;\n out += blank(source.slice(i, stop));\n i = stop;\n continue;\n }\n if (ch === \"/\" && next === \"*\") {\n const end = source.indexOf(\"*/\", i + 2);\n const stop = end === -1 ? source.length : end + 2;\n out += blank(source.slice(i, stop));\n i = stop;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n // Up to the closing quote; an unterminated one stops at the newline.\n let j = i + 1;\n while (j < source.length && source[j] !== ch && source[j] !== \"\\n\") {\n j += source[j] === \"\\\\\" ? 2 : 1;\n }\n const close = source[j] === ch ? ch : \"\";\n out += ch + literal(source.slice(i + 1, Math.min(j, source.length)));\n out += close;\n i = close ? j + 1 : j;\n continue;\n }\n if (ch === \"`\") {\n out += \"`\";\n i++;\n templateText();\n continue;\n }\n if (holes.length > 0 && ch === \"{\") holes[holes.length - 1]++;\n if (holes.length > 0 && ch === \"}\") {\n if (holes[holes.length - 1] === 0) {\n holes.pop();\n out += \"}\";\n i++;\n templateText();\n continue;\n }\n holes[holes.length - 1]--;\n }\n out += ch;\n i++;\n }\n return out;\n}\n\n/** Blank out `//` and block comments, keeping string and template literals\n * (URLs contain `//`) and every newline, so line-anchored checks still see\n * the code's own lines. A JSDoc `import(\"…\")` type is a comment, not code. */\nexport function stripComments(source: string): string {\n return scanSource(source, \"keep\");\n}\n\n/** Blank out comments and the contents of string literals and\n * template-literal text, so a word inside a string (a URL, a description,\n * an apostrophe in template text) is neither mistaken for code nor able to\n * hide code. Template `${…}` holes are code and are kept. */\nfunction blankLiterals(source: string): string {\n return scanSource(source, \"blank\");\n}\n\n// Not after `.`/identifier chars: `base.runner.process.args` is a property.\nconst PROCESS_ACCESS = /(?<![.\\w$])process\\s*(?:\\?\\.|\\.|\\[)/;\n\n/** Host files and generated outputs.js are data: reading the environment\n * through `process.` is banned (typed-host-configs decision 9). Environment\n * values go through `$env`, which resolves at start in the resolving\n * process. Comments are already stripped, so a mention there is fine. */\nfunction rejectProcessAccess(source: string, file: string): void {\n const match = PROCESS_ACCESS.exec(blankLiterals(source));\n if (!match) return;\n const line = source.slice(0, match.index).split(\"\\n\").length;\n throw new HostLoadError(\n `${file}:${line} reads \\`process.\\` — host files cannot read the environment directly.`,\n 'Use an $env token instead: { $env: \"NAME\" } (fails when unset), or { $env: { name: \"NAME\", optional: true } } as a property value to omit the property when unset. It resolves when the host starts.',\n );\n}\n\n/** The imports a host file makes, after linting it. */\nexport interface HostImports {\n /** Sibling hosts whose `host.js` the file imports. */\n hosts: string[];\n /** Sibling hosts whose generated `outputs.js` the file imports. */\n outputs: string[];\n}\n\n/** Lints a host file and returns what it imports. Rejects every import\n * except the project's powerhouse.config.json, SIBLING host files (R1:\n * derived compositions) and sibling generated outputs.js token trees; any\n * dynamic `import(...)` or `require(...)`; and any `process.` access.\n * Source-level enforcement: the JSON round trip below is the hard gate; this\n * one produces the better error. */\nexport function scanHostImports(rawSource: string, file: string): HostImports {\n const source = stripComments(rawSource);\n const imports: HostImports = { hosts: [], outputs: [] };\n for (const match of source.matchAll(\n /^\\s*import\\b[^;'\"]*?from\\s+[\"']([^\"']+)[\"']/gm,\n )) {\n const specifier = match[1];\n if (specifier.endsWith(CONFIG_IMPORT_SUFFIX)) continue;\n const sibling = SIBLING_IMPORT.exec(specifier);\n if (sibling) {\n (sibling[2] === HOST_FILE ? imports.hosts : imports.outputs).push(\n sibling[1],\n );\n continue;\n }\n throw new HostLoadError(\n `${file} imports \"${specifier}\" — a host file may only import the project's powerhouse.config.json, sibling hosts/<name>/host.js files or generated hosts/<name>/${OUTPUTS_FILE} token trees.`,\n \"Host files are static projections; code belongs in plugins or the runner.\",\n );\n }\n if (/^\\s*import\\s+[\"']/m.test(source)) {\n throw new HostLoadError(\n `${file} contains a side-effect import — a host file may only import the project's powerhouse.config.json or sibling host files.`,\n );\n }\n if (/\\bimport\\s*\\(/.test(source) || /\\brequire\\s*\\(/.test(source)) {\n throw new HostLoadError(\n `${file} uses dynamic import()/require() — host files are static data.`,\n );\n }\n rejectProcessAccess(source, file);\n return imports;\n}\n\n/** {@link scanHostImports}, returning only the sibling host names (for cycle\n * detection). */\nexport function lintHostImports(rawSource: string, file: string): string[] {\n return scanHostImports(rawSource, file).hosts;\n}\n\n/** A generated `outputs.js` is plain data: no imports of any kind, no\n * dynamic import/require, no `process.`. */\nexport function lintOutputsFile(rawSource: string, file: string): void {\n const source = stripComments(rawSource);\n if (\n /^\\s*import\\b/m.test(source) ||\n /^\\s*export\\b[^;]*?\\bfrom\\s+[\"']/m.test(source) ||\n /\\bimport\\s*\\(/.test(source) ||\n /\\brequire\\s*\\(/.test(source)\n ) {\n throw new HostLoadError(\n `${file} imports a module — a generated ${OUTPUTS_FILE} is plain data.`,\n \"Regenerate it with `ph generate hosts` instead of editing it.\",\n );\n }\n rejectProcessAccess(source, file);\n}\n\n/** Walks the sibling-import graph from `hostName`, linting every visited file\n * (and every outputs.js it imports) and failing on a cycle (an ESM circular\n * would otherwise surface as an undefined default export with no useful\n * message). Returns the hosts whose outputs.js the graph imports, sorted. */\nexport function lintHostImportGraph(\n hostsDir: string,\n hostName: string,\n): string[] {\n const state = new Map<string, \"visiting\" | \"done\">();\n const producers = new Set<string>();\n const visit = (name: string, chain: string[]): void => {\n const mark = state.get(name);\n if (mark === \"done\") return;\n if (mark === \"visiting\") {\n throw new HostLoadError(\n `Host import cycle: ${[...chain, name].map((n) => `hosts/${n}`).join(\" -> \")}.`,\n \"Hoist the shared data into one host (or powerhouse.config.json) instead of importing both ways.\",\n );\n }\n const file = path.join(hostsDir, name, HOST_FILE);\n if (!existsSync(file)) {\n throw new HostLoadError(\n `hosts/${chain[chain.length - 1] ?? name} imports sibling \"hosts/${name}/host.js\", which does not exist.`,\n );\n }\n state.set(name, \"visiting\");\n const imports = scanHostImports(readFileSync(file, \"utf8\"), file);\n for (const producer of imports.outputs) {\n if (producers.has(producer)) continue;\n const outputsFile = path.join(hostsDir, producer, OUTPUTS_FILE);\n if (!existsSync(outputsFile)) {\n throw new HostLoadError(\n `hosts/${name}/host.js imports \"hosts/${producer}/${OUTPUTS_FILE}\", which does not exist.`,\n GENERATE_HINT,\n );\n }\n lintOutputsFile(readFileSync(outputsFile, \"utf8\"), outputsFile);\n producers.add(producer);\n }\n for (const sibling of imports.hosts) visit(sibling, [...chain, name]);\n state.set(name, \"done\");\n };\n visit(hostName, []);\n return [...producers].sort();\n}\n\n/** Returns the path of the first value that would not survive a JSON round\n * trip, or undefined when the object is fully static. */\nexport function findNonStaticValue(\n value: unknown,\n trail = \"\",\n): string | undefined {\n if (value === null) return undefined;\n const kind = typeof value;\n if (kind === \"string\" || kind === \"number\" || kind === \"boolean\") {\n return undefined;\n }\n if (kind !== \"object\") {\n return `${trail || \"<root>\"} (${kind})`;\n }\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const hit = findNonStaticValue(value[i], `${trail}[${i}]`);\n if (hit) return hit;\n }\n return undefined;\n }\n const proto: unknown = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) {\n return `${trail || \"<root>\"} (non-plain object)`;\n }\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n const hit = findNonStaticValue(child, trail ? `${trail}.${key}` : key);\n if (hit) return hit;\n }\n return undefined;\n}\n\nexport type { HostDefinition } from \"./host-schemas.js\";\n\nexport interface LoadedHost {\n name: string;\n dir: string;\n file: string;\n host: HostDefinition;\n}\n\nfunction assertHostShape(\n host: Record<string, unknown>,\n file: string,\n): asserts host is HostDefinition & Record<string, unknown> {\n if (typeof host.name !== \"string\" || host.name.length === 0) {\n throw new HostLoadError(`${file}: \\`name\\` must be a non-empty string.`);\n }\n const runner = host.runner;\n if (\n runner === null ||\n typeof runner !== \"object\" ||\n typeof (runner as Record<string, unknown>).module !== \"string\"\n ) {\n throw new HostLoadError(\n `${file}: \\`runner\\` must be an object with a \\`module\\` specifier string.`,\n );\n }\n if (host.reactor !== undefined && host.children !== undefined) {\n throw new HostLoadError(\n `${file}: \\`reactor\\` and \\`children\\` are mutually exclusive — a host is a reactor runner or a compound runner, never both.`,\n );\n }\n}\n\nexport async function loadHost(\n projectRoot: string,\n hostName: string,\n): Promise<LoadedHost> {\n return importHost(projectRoot, hostName, true);\n}\n\nasync function importHost(\n projectRoot: string,\n hostName: string,\n checkOutputs: boolean,\n): Promise<LoadedHost> {\n const probe = probeHostsFolder(projectRoot);\n if (probe.kind === \"absent\") {\n throw new HostLoadError(\n `No hosts/ folder found in ${projectRoot}.`,\n \"New projects get one from `ph init`; in an existing project, create hosts/<name>/host.js.\",\n );\n }\n if (probe.kind === \"empty\") {\n throw new HostLoadError(\n `hosts/ exists at ${probe.dir} but contains no <name>/host.js.`,\n \"An empty hosts/ folder defines no hosts; add a host definition or remove the folder.\",\n );\n }\n if (!probe.hosts.includes(hostName)) {\n throw new HostLoadError(\n `Unknown host \"${hostName}\". Available hosts: ${probe.hosts.join(\", \")}.`,\n );\n }\n\n const file = path.join(probe.dir, hostName, HOST_FILE);\n const producers = lintHostImportGraph(probe.dir, hostName);\n // Step 1 of the loader pipeline: a stale outputs.js fails before the host\n // is evaluated (its token tree may name outputs that no longer exist).\n if (checkOutputs) {\n for (const producer of producers) {\n await assertOutputsFileFresh(projectRoot, probe.dir, hostName, producer);\n }\n }\n\n const module = (await import(pathToFileURL(file).href)) as {\n default?: unknown;\n };\n const host = module.default;\n if (host === null || typeof host !== \"object\" || Array.isArray(host)) {\n throw new HostLoadError(\n `${file} must default-export the host object (\\`export default { name, runner, ... }\\`).`,\n );\n }\n\n const nonStatic = findNonStaticValue(host);\n if (nonStatic) {\n throw new HostLoadError(\n `${file} exports a non-static value at \\`${nonStatic}\\` — host files must survive a JSON round trip.`,\n \"Runtime behavior belongs in the runner; host files only carry data.\",\n );\n }\n\n assertHostShape(host as Record<string, unknown>, file);\n return {\n name: hostName,\n dir: path.dirname(file),\n file,\n host: host as HostDefinition,\n };\n}\n\n/* ---------------------------------------------------- generated outputs.js */\n\n/** What `ph generate hosts` derives a host's outputs.js from, plus the hash\n * of exactly those inputs (embedded in the file; the loader recomputes it). */\nexport interface HostOutputsDescription {\n /** The producer's folder name: the `host` of every `$output` token. */\n host: string;\n runnerModule: string;\n /** JSON Schema of the runner's `outputsSchema` (output side, no `$schema`). */\n outputsSchema: Record<string, unknown>;\n /** Declared LOCAL drive slugs: `reactor.drives` without remote drives,\n * plus drives the host's plugins contribute (any verb). Sorted, unique.\n * These are the known keys of the `drives` record output. */\n drives: string[];\n hash: string;\n}\n\nconst OUTPUTS_HASH_EXPORT = /^export const outputsHash = \"([^\"]+)\";$/m;\n\n/** The hash a generated outputs.js carries, or undefined. */\nexport function readOutputsFileHash(source: string): string | undefined {\n return OUTPUTS_HASH_EXPORT.exec(source)?.[1];\n}\n\nfunction canonicalJson(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map(canonicalJson).join(\",\")}]`;\n }\n if (value !== null && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, child]) => child !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`).join(\",\")}}`;\n }\n return JSON.stringify(value);\n}\n\n/** sha256 over the canonical JSON of the generator's inputs. The host name\n * is one: every token in the file carries it, so a copied or renamed host\n * folder makes its outputs.js stale. */\nexport function computeOutputsHash(input: {\n host: string;\n runnerModule: string;\n outputsSchema: Record<string, unknown>;\n drives: readonly string[];\n}): string {\n const digest = createHash(\"sha256\")\n .update(\n canonicalJson({\n v: 1,\n host: input.host,\n runnerModule: input.runnerModule,\n outputsSchema: input.outputsSchema,\n drives: [...new Set(input.drives)].sort(),\n }),\n )\n .digest(\"hex\");\n return `sha256:${digest.slice(0, 32)}`;\n}\n\nfunction isZodSchema(value: unknown): value is z.ZodType {\n return value !== null && typeof value === \"object\" && \"_zod\" in value;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/** Local (non-remote) slugs from a drive declaration list. */\nfunction localDriveSlugs(drives: unknown): string[] {\n if (!Array.isArray(drives)) return [];\n return drives.flatMap((drive) =>\n isRecord(drive) &&\n typeof drive.slug === \"string\" &&\n drive.remote === undefined\n ? [drive.slug]\n : [],\n );\n}\n\n/**\n * Describes the outputs a host's creation produces, for `ph generate hosts`\n * and the loader's staleness check: the runner's `outputsSchema` as JSON\n * Schema and the host's declared local drives (the keys `drives.<slug>` of a\n * switchboard-like runner). Returns undefined when the runner exports no\n * `outputsSchema` (the host produces nothing a token can reference).\n *\n * Plugin-contributed drives are collected across every verb (verb scoping\n * is ignored: a drive any verb serves is referenceable). Plugins the project\n * tree cannot resolve contribute nothing, exactly as at boot. The implicit\n * default drive a switchboard serves when it declares none is NOT a known\n * key (it is not declared); reach it with a literal `$output` token.\n */\nexport async function describeHostOutputs(\n projectRoot: string,\n hostName: string,\n): Promise<HostOutputsDescription | undefined> {\n const { host, file } = await importHost(projectRoot, hostName, false);\n const runnerModule = host.runner.module;\n const runner = await resolveRunnerModule(projectRoot, runnerModule);\n const schema = runner.outputsSchema;\n if (!isZodSchema(schema)) return undefined;\n const { $schema: _dialect, ...outputsSchema } = z.toJSONSchema(schema, {\n io: \"output\",\n unrepresentable: \"any\",\n }) as Record<string, unknown>;\n\n const reactor = (host as { reactor?: unknown }).reactor;\n const drives = localDriveSlugs(isRecord(reactor) ? reactor.drives : []);\n const entries: PluginEntryData[] = (host.runner.plugins ?? []).map((entry) =>\n typeof entry === \"string\" ? entry : { ...entry, verbs: \"*\" },\n );\n if (entries.length > 0) {\n const plan = await resolvePluginContributions(\n projectRoot,\n \"*\",\n entries,\n path.relative(projectRoot, file),\n );\n drives.push(\n ...localDriveSlugs(plan.drives.map((drive) => drive.declaration)),\n );\n }\n const sortedDrives = [...new Set(drives)].sort();\n return {\n host: hostName,\n runnerModule,\n outputsSchema,\n drives: sortedDrives,\n hash: computeOutputsHash({\n host: hostName,\n runnerModule,\n outputsSchema,\n drives: sortedDrives,\n }),\n };\n}\n\nasync function assertOutputsFileFresh(\n projectRoot: string,\n hostsDir: string,\n consumer: string,\n producer: string,\n): Promise<void> {\n const rel = `hosts/${producer}/${OUTPUTS_FILE}`;\n const actual = readOutputsFileHash(\n readFileSync(path.join(hostsDir, producer, OUTPUTS_FILE), \"utf8\"),\n );\n if (!existsSync(path.join(hostsDir, producer, HOST_FILE))) {\n throw new HostLoadError(\n `hosts/${consumer} imports ${rel}, but there is no hosts/${producer}/host.js to produce it.`,\n \"Delete the orphaned outputs.js and fix the import.\",\n );\n }\n const description = await describeHostOutputs(projectRoot, producer);\n if (!description) {\n throw new HostLoadError(\n `hosts/${consumer} imports ${rel}, but hosts/${producer}'s runner declares no outputsSchema, so it produces no outputs.`,\n );\n }\n if (actual !== description.hash) {\n throw new HostLoadError(\n `${rel} is stale (its producer's outputsSchema or declared drives changed since it was generated); run \\`ph generate hosts\\`.`,\n actual === undefined\n ? `${rel} carries no outputsHash export; it was not generated by \\`ph generate hosts\\`.`\n : `expected ${description.hash}, found ${actual}.`,\n );\n }\n}\n","import { RunnerError } from \"./runner-resolver.js\";\n\n/**\n * The arguments of one invocation: what follows `ph run <host> [verb]` and\n * `ph run` does not read itself. A runner declares the ones it accepts as its\n * `argsSchema` export; anything else fails before the runner starts.\n */\n\n/** The arguments a runner accepts, as typed (`--port`, `-w`). Structural: a\n * runner builds it from its own argument definitions, and this package needs\n * no argument parser. */\nexport interface RunnerArgsSchema {\n /** Take a value: `--port 4001` or `--port=4001`. */\n options: readonly string[];\n /** Switches: `--strictPort`. */\n flags: readonly string[];\n /** The name a compound's member takes an option under, e.g.\n * `{ \"--switchboard-port\": \"--port\" }`. In a compound the plain name is\n * refused: it would reach every member that has it. */\n memberOptions?: Readonly<Record<string, string>>;\n /** Retired switches and what to do instead: accepted, one warning, no\n * effect. */\n retired?: Readonly<Record<string, string>>;\n}\n\nconst isStrings = (value: unknown): value is readonly string[] =>\n Array.isArray(value) && value.every((item) => typeof item === \"string\");\n\nconst isStringRecord = (value: unknown): value is Record<string, string> =>\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.values(value).every((item) => typeof item === \"string\");\n\nexport function isRunnerArgsSchema(value: unknown): value is RunnerArgsSchema {\n if (typeof value !== \"object\" || value === null) return false;\n const schema = value as Record<string, unknown>;\n return (\n isStrings(schema.options) &&\n isStrings(schema.flags) &&\n (schema.memberOptions === undefined ||\n isStringRecord(schema.memberOptions)) &&\n (schema.retired === undefined || isStringRecord(schema.retired))\n );\n}\n\nexport interface SplitRunArgv {\n host?: string;\n verb?: string;\n /** `ph run`'s own arguments (`--debug`, `--explain <topic>`, help). */\n own: string[];\n /** Everything else, in order: the runner's. */\n argv: string[];\n}\n\nconst OWN_FLAGS = new Set([\"--debug\", \"--help\", \"-h\"]);\n\n/**\n * Splits what follows `ph run`. The host and the verb come before the\n * runner's arguments: `ph run` does not know which of those take a value, so\n * a bare word after the first of them belongs to the runner. A literal `--`\n * hands over everything after it.\n */\nexport function splitRunArgv(args: readonly string[]): SplitRunArgv {\n const result: SplitRunArgv = { own: [], argv: [] };\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === \"--\") {\n result.argv.push(...args.slice(i + 1));\n break;\n }\n if (OWN_FLAGS.has(arg) || arg.startsWith(\"--explain=\")) {\n result.own.push(arg);\n } else if (arg === \"--explain\") {\n result.own.push(...args.slice(i, i + 2));\n i++;\n } else if (arg.startsWith(\"-\") || result.argv.length > 0) {\n result.argv.push(arg);\n } else if (result.host === undefined) {\n result.host = arg;\n } else if (result.verb === undefined) {\n result.verb = arg;\n } else {\n result.argv.push(arg);\n }\n }\n return result;\n}\n\ninterface ArgvEntry {\n /** The argument as typed, without its value: `--port`. */\n name: string;\n /** Its tokens: `[\"--port\", \"4001\"]` or `[\"--port=4001\"]`. */\n tokens: string[];\n}\n\nfunction entriesOf(\n argv: readonly string[],\n takesValue: (name: string) => boolean,\n where: string,\n): ArgvEntry[] {\n const entries: ArgvEntry[] = [];\n for (let i = 0; i < argv.length; i++) {\n const token = argv[i];\n if (token === \"--\") continue;\n const equals = token.startsWith(\"-\") ? token.indexOf(\"=\") : -1;\n const name = equals === -1 ? token : token.slice(0, equals);\n if (equals === -1 && takesValue(name)) {\n if (i + 1 >= argv.length) {\n throw new RunnerError(`${where}: ${name} needs a value.`);\n }\n entries.push({ name, tokens: [token, argv[i + 1]] });\n i++;\n } else {\n entries.push({ name, tokens: [token] });\n }\n }\n return entries;\n}\n\nfunction warnRetired(name: string, instead: string): void {\n console.warn(`${name} is retired and has no effect: ${instead}`);\n}\n\nconst acceptedBy = (schema: RunnerArgsSchema): string[] => [\n ...schema.options,\n ...schema.flags,\n];\n\nexport interface RunnerArgvTarget {\n /** The host's folder name under hosts/. */\n host: string;\n /** The runner's specifier. */\n runner: string;\n /** The runner module's `argsSchema` export. */\n schema: unknown;\n}\n\n/**\n * The arguments a standalone runner receives as `ctx.argv`: `argv` checked\n * against the runner's schema, retired switches warned about and dropped.\n * Nothing is dropped silently: an argument the runner does not accept, or any\n * argument for a runner without a schema, fails.\n */\nexport function checkRunnerArgv(\n argv: readonly string[],\n target: RunnerArgvTarget,\n): string[] {\n if (argv.length === 0) return [];\n const where = `hosts/${target.host}`;\n const schema = target.schema;\n if (!isRunnerArgsSchema(schema)) {\n throw new RunnerError(\n `${where}: its runner ${target.runner} accepts no arguments, but got: ${argv.join(\" \")}`,\n \"Set these in the host file instead.\",\n );\n }\n const options = new Set(schema.options);\n const accepted = new Set(acceptedBy(schema));\n const kept: string[] = [];\n const unknown: string[] = [];\n for (const entry of entriesOf(argv, (name) => options.has(name), where)) {\n const instead = schema.retired?.[entry.name];\n if (accepted.has(entry.name)) {\n kept.push(...entry.tokens);\n } else if (instead !== undefined) {\n warnRetired(entry.name, instead);\n } else {\n unknown.push(entry.name);\n }\n }\n if (unknown.length > 0) {\n throw new RunnerError(\n `${where}: its runner ${target.runner} does not accept ${unknown.join(\", \")}.`,\n `It accepts: ${[...accepted].join(\", \") || \"no arguments\"}.`,\n );\n }\n return kept;\n}\n\nexport interface CompoundArgvMember {\n /** The member's key in the compound's `children`. */\n key: string;\n /** The member runner's specifier. */\n runner: string;\n /** The member runner module's `argsSchema` export. */\n schema: unknown;\n}\n\n/**\n * A compound's arguments, per member key: each member gets the ones its\n * runner accepts. A member option arrives under its member name\n * (`--switchboard-port 4001` reaches that member as `--port 4001`). An\n * argument no member accepts fails, as does one that would set the same\n * option on several members.\n */\nexport function splitCompoundArgv(\n argv: readonly string[],\n host: string,\n members: readonly CompoundArgvMember[],\n): Map<string, string[]> {\n const perMember = new Map<string, string[]>(members.map((m) => [m.key, []]));\n if (argv.length === 0) return perMember;\n const where = `hosts/${host}`;\n const schemas = members.flatMap((m) =>\n isRunnerArgsSchema(m.schema) ? [{ key: m.key, schema: m.schema }] : [],\n );\n // plain option name -> the member names it goes by\n const memberNames = new Map<string, string[]>();\n for (const { schema } of schemas) {\n for (const [alias, option] of Object.entries(schema.memberOptions ?? {})) {\n const aliases = memberNames.get(option) ?? [];\n if (!aliases.includes(alias)) aliases.push(alias);\n memberNames.set(option, aliases);\n }\n }\n const takesValue = (name: string) =>\n schemas.some(\n ({ schema }) =>\n schema.options.includes(name) ||\n schema.memberOptions?.[name] !== undefined,\n );\n const warned = new Set<string>();\n const unknown: string[] = [];\n for (const entry of entriesOf(argv, takesValue, where)) {\n const { name, tokens } = entry;\n const named = schemas.filter(\n ({ schema }) => schema.memberOptions?.[name] !== undefined,\n );\n if (named.length > 1) {\n throw new RunnerError(\n `${where}: ${name} matches the members ${named.map((m) => m.key).join(\", \")}.`,\n \"Set the option in each member's host file instead.\",\n );\n }\n if (named.length === 1) {\n const { key, schema } = named[0];\n const option = schema.memberOptions?.[name] ?? name;\n // `--switchboard-port=4001` keeps its `=4001`\n const first = option + tokens[0].slice(name.length);\n perMember.get(key)?.push(first, ...tokens.slice(1));\n continue;\n }\n const aliases = memberNames.get(name);\n if (aliases) {\n throw new RunnerError(\n `${where}: ${name} does not say which member it is for.`,\n `Use ${aliases.join(\" or \")}.`,\n );\n }\n const takers = schemas.filter(({ schema }) =>\n acceptedBy(schema).includes(name),\n );\n if (takers.length > 0) {\n for (const { key } of takers) perMember.get(key)?.push(...tokens);\n continue;\n }\n const retired = schemas.find(\n ({ schema }) => schema.retired?.[name] !== undefined,\n );\n if (retired) {\n if (!warned.has(name)) {\n warned.add(name);\n warnRetired(name, retired.schema.retired?.[name] ?? \"\");\n }\n continue;\n }\n unknown.push(name);\n }\n if (unknown.length > 0) {\n const accepted = members.map((m) => {\n if (!isRunnerArgsSchema(m.schema)) {\n return ` - ${m.key} (${m.runner}): no arguments`;\n }\n const schema = m.schema;\n const scoped = new Set(Object.values(schema.memberOptions ?? {}));\n const names = [\n ...Object.keys(schema.memberOptions ?? {}),\n ...acceptedBy(schema).filter((name) => !scoped.has(name)),\n ];\n return ` - ${m.key} (${m.runner}): ${names.join(\", \") || \"no arguments\"}`;\n });\n throw new RunnerError(\n `${where}: no member accepts ${unknown.join(\", \")}. The members accept:\\n${accepted.join(\"\\n\")}`,\n );\n }\n return perMember;\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 { resolvePhDir } from \"@powerhousedao/shared/clis/ph-dir\";\nimport { execFileSync } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { HOST_NAME_MESSAGE, hostNameSchema } from \"./host-schemas.js\";\nimport { runRecordSchema, type RunRecord } from \"./run-record-schema.js\";\n\nexport {\n runRecordMemberSchema,\n runRecordSchema,\n type RunRecord,\n type RunRecordMember,\n} from \"./run-record-schema.js\";\n\n/**\n * Record I/O for `.ph/run/<host>.json`, keyed by host name so N hosts\n * (vetra, desktop, …) coexist. The record shape is run-record-schema.ts (v2).\n */\n\nexport type RunProbe =\n | { status: \"none\" }\n | { status: \"stale\"; record: RunRecord }\n | { status: \"live\"; record: RunRecord }\n | { status: \"foreign\"; record: RunRecord };\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\n// Under the project's .ph tree — relocated with it by PH_USER_DATA_DIR. The\n// readers take `env` so a launcher can read a child's records.\nconst runDir = (projectDir: string, env: Env = process.env) =>\n path.join(resolvePhDir(projectDir, env), \"run\");\nfunction recordPath(projectDir: string, hostName: string, env?: Env): string {\n const dir = runDir(projectDir, env);\n const file = path.resolve(dir, `${hostName}.json`);\n if (\n !hostNameSchema.safeParse(hostName).success ||\n path.dirname(file) !== path.resolve(dir)\n ) {\n throw new Error(\n `\"${hostName}\" can't name a run record. ${HOST_NAME_MESSAGE}`,\n );\n }\n return file;\n}\n\nexport function readRunRecord(\n projectDir: string,\n hostName: string,\n env: Env = process.env,\n): RunRecord | undefined {\n let raw: unknown;\n try {\n raw = JSON.parse(\n fs.readFileSync(recordPath(projectDir, hostName, env), \"utf8\"),\n );\n } catch {\n return undefined;\n }\n // v1 and foreign-shaped records read as \"not running\" (3.6).\n const parsed = runRecordSchema.safeParse(raw);\n return parsed.success ? parsed.data : undefined;\n}\n\n/** Every valid v2 record under `.ph/run/` (invalid and v1 files skipped). */\nexport function listRunRecords(\n projectDir: string,\n env: Env = process.env,\n): RunRecord[] {\n let files: string[];\n try {\n files = fs.readdirSync(runDir(projectDir, env));\n } catch {\n return [];\n }\n return files\n .filter((file) => file.endsWith(\".json\"))\n .flatMap((file) => {\n const record = readRunRecord(\n projectDir,\n file.slice(0, -\".json\".length),\n env,\n );\n return record ? [record] : [];\n });\n}\n\n/** The project identity the live/foreign probe compares: package.json\n * `name`, else the folder name. */\nexport function readProjectName(projectDir: string): string {\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(projectDir, \"package.json\"), \"utf8\"),\n ) as { name?: unknown };\n if (typeof pkg.name === \"string\" && pkg.name) return pkg.name;\n } catch {\n // fall through\n }\n return path.basename(path.resolve(projectDir));\n}\n\nexport function writeRunRecord(projectDir: string, record: RunRecord): void {\n const target = recordPath(projectDir, record.host);\n const valid = runRecordSchema.parse(record);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, `${JSON.stringify(valid, null, 2)}\\n`);\n}\n\nexport function clearRunRecord(\n projectDir: string,\n hostName: string,\n env: Env = process.env,\n): void {\n try {\n fs.rmSync(recordPath(projectDir, hostName, env));\n } catch {\n // already gone\n }\n}\n\nexport function isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM = the process exists but belongs to another user.\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/** When a process started, in ms since the epoch; undefined when the\n * platform does not tell (the process is gone, the tool is missing). */\nexport function processStartedAtMs(pid: number): number | undefined {\n try {\n if (process.platform === \"linux\") {\n // Field 22 of /proc/<pid>/stat: start in clock ticks (100 a second)\n // after boot; the command (field 2) may hold spaces, so count from\n // its closing bracket.\n const stat = fs.readFileSync(`/proc/${pid}/stat`, \"utf8\");\n const ticks = Number(\n stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \")[19],\n );\n const boot = /^btime (\\d+)$/m.exec(fs.readFileSync(\"/proc/stat\", \"utf8\"));\n if (!boot || !Number.isFinite(ticks)) return undefined;\n return (Number(boot[1]) + ticks / 100) * 1000;\n }\n const [command, args] =\n process.platform === \"win32\"\n ? [\n \"powershell.exe\",\n [\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-Command\",\n `(Get-Process -Id ${pid}).StartTime.ToUniversalTime().ToString('o')`,\n ],\n ]\n : [\"ps\", [\"-o\", \"lstart=\", \"-p\", String(pid)]];\n const out = execFileSync(command, args, {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: 10_000,\n windowsHide: true,\n env: { ...process.env, LC_ALL: \"C\" },\n }).trim();\n const started = Date.parse(out);\n return Number.isFinite(started) ? started : undefined;\n } catch {\n return undefined;\n }\n}\n\n// A record is written by the process it names, so that process started\n// before `startedAt`. The slack covers clocks that count in seconds.\nconst START_SLACK_MS = 5_000;\n// The records whose pid was found to be the recording process: asked once\n// per record, since the answer costs a child process on Windows and macOS.\nconst confirmedRecords = new Set<string>();\n\n/** True when the recorded pid now names another process: one that started\n * after the record was written. False when that cannot be told. */\nfunction isPidReused(record: RunRecord): boolean {\n if (record.pid === process.pid) return false;\n const recordedAt = Date.parse(record.startedAt);\n if (!Number.isFinite(recordedAt)) return false;\n const key = `${record.pid}:${record.startedAt}`;\n if (confirmedRecords.has(key)) return false;\n const startedAt = processStartedAtMs(record.pid);\n if (startedAt === undefined) return false;\n if (startedAt > recordedAt + START_SLACK_MS) return true;\n confirmedRecords.add(key);\n return false;\n}\n\n/**\n * Decide whether the recorded instance is this project's live host.\n *\n * pid liveness alone proves nothing (pids are reused): a live pid counts\n * only when its process started before the record was written. The recorded\n * projectName is what separates \"my instance\" from \"a different project that\n * happens to hold this storage root\" — the confusion the vetra lock exists to\n * prevent. A stale record (dead or reused pid) is reported so the caller can\n * clear it; a foreign one (live pid, different project) is left alone.\n */\nexport function probeRun(\n projectDir: string,\n hostName: string,\n projectName: string,\n env: Env = process.env,\n): RunProbe {\n const record = readRunRecord(projectDir, hostName, env);\n if (!record) return { status: \"none\" };\n if (!isPidAlive(record.pid) || isPidReused(record)) {\n return { status: \"stale\", record };\n }\n if (record.projectName !== projectName) return { status: \"foreign\", record };\n return { status: \"live\", record };\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 path from \"node:path\";\nimport { substituteBuiltinEnv } from \"./env-substitution.js\";\n\n/**\n * `${userData}` resolution for host files (desktop shape): storage paths in a\n * host must not derive from the instance name (renames must stay safe), so\n * the host file writes `${userData}/.ph/reactor-storage` and the RUNNER\n * resolves it at start. `${userData}` is a PROJECT-SHAPED root: its `.ph`\n * subtree carries the same names the classic commands use under\n * `<project>/.ph` (see `resolvePhDir`). In the CLI it IS the project root, so\n * `ph run desktop` in a project shares the one `.ph` tree `ph vetra` uses;\n * a shell (Tauri) points it at the OS profile via PH_USER_DATA_DIR, and the\n * whole `.ph` tree — stores, identity, run records — follows.\n */\nexport function defaultUserDataDir(\n projectRoot: string,\n env: Record<string, string | undefined> = process.env,\n): string {\n return env.PH_USER_DATA_DIR ?? path.resolve(projectRoot);\n}\n\n/** Deep-substitute `${userData}` in every string of a JSON-shaped value.\n * Non-strings pass through; the input is never mutated. */\nexport function resolveUserDataPlaceholders<T>(value: T, userData: string): T {\n return substituteBuiltinEnv(value, { userData });\n}\n","import path from \"node:path\";\nimport { loadHost } from \"../host-loader.js\";\nimport { defaultUserDataDir } from \"../placeholders.js\";\nimport { isPidAlive, listRunRecords, probeRun } from \"../run-record.js\";\nimport { resolveRunnerModule, type RunnerModule } from \"../runner-resolver.js\";\nimport type { OutputRef, OutputsSchemaLookup } from \"./declared.js\";\nimport type { OutputSource, ResolveSources } from \"./resolve.js\";\n\n/**\n * Node adapters for the resolver: producer discovery (a token names a host\n * by FOLDER; run records are keyed by the host's `name`, so the producer's\n * host.js is loaded to map one to the other), the standalone run-record\n * output source, and the process environment.\n */\n\nexport interface ProducerInfo {\n /** The folder a token names (`hosts/<folder>/`). */\n folder: string;\n /** The producer host's `name` (its run-record key). */\n name: string;\n specifier: string;\n runner: RunnerModule;\n}\n\n/** Producers by folder; a folder that fails to load carries its error. */\nexport type ProducerMap = ReadonlyMap<string, ProducerInfo | { error: string }>;\n\n/** Load every producer host a set of refs names (each once). */\nexport async function loadProducers(\n projectRoot: string,\n refs: readonly OutputRef[],\n): Promise<ProducerMap> {\n const producers = new Map<string, ProducerInfo | { error: string }>();\n for (const { host: folder } of refs) {\n if (producers.has(folder)) continue;\n try {\n const loaded = await loadHost(projectRoot, folder);\n const specifier = loaded.host.runner.module;\n producers.set(folder, {\n folder,\n name: loaded.host.name,\n specifier,\n runner: await resolveRunnerModule(projectRoot, specifier),\n });\n } catch (error) {\n producers.set(folder, {\n error: `names host \"${folder}\", which cannot be loaded: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n }\n return producers;\n}\n\n/** The outputs schema of a runner module, or why it has none. */\nexport function runnerOutputsSchema(\n runner: RunnerModule,\n specifier: string,\n label: string,\n): OutputsSchemaLookup {\n const schema = runner.outputsSchema;\n if (schema === undefined || schema === null) {\n return {\n error: `${label} runs \"${specifier}\", which exports no outputsSchema, so it produces no outputs a token can read.`,\n };\n }\n return { schema, label: `\"${specifier}\" (${label})` };\n}\n\n/** Declared-validation lookup for a standalone host's producers. */\nexport function producerOutputsSchemas(\n producers: ProducerMap,\n): (ref: OutputRef) => OutputsSchemaLookup {\n return (ref) => {\n const info = producers.get(ref.host);\n if (!info)\n return { error: `names host \"${ref.host}\", which was not loaded.` };\n if (\"error\" in info) return { error: info.error };\n return runnerOutputsSchema(\n info.runner,\n info.specifier,\n `host \"${ref.host}\"`,\n );\n };\n}\n\n/** Further `.ph` roots whose live run records a standalone `$output` reads\n * (`path.delimiter`-separated): a launcher that gives each child its own\n * PH_USER_DATA_DIR names its siblings' here. Locks never read them. */\nexport const OUTPUT_DATA_DIRS_ENV = \"PH_OUTPUT_DATA_DIRS\";\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\n/** The other roots, each once, never the process's own. */\nfunction siblingEnvs(projectRoot: string, env: Env): Env[] {\n const own = path.resolve(defaultUserDataDir(projectRoot, env));\n const dirs = new Set(\n (env[OUTPUT_DATA_DIRS_ENV] ?? \"\")\n .split(path.delimiter)\n .filter((dir) => dir !== \"\")\n .map((dir) => path.resolve(dir)),\n );\n return [...dirs]\n .filter((dir) => dir !== own)\n .map((dir) => ({ PH_USER_DATA_DIR: dir }));\n}\n\n/**\n * Standalone `$output` source: the producer's live v2 run record. Its own\n * standalone record under the process's `.ph` root first (keyed by the\n * producer's `name`); else exactly one of: a standalone record under a\n * PH_OUTPUT_DATA_DIRS root, or a member running that host in a live compound\n * of this project under any root. A missing, stale, foreign or output-less\n * record means \"not running\", and the lookup fails naming the producer and\n * how to start it (no fallback to the producer's declared config, no\n * waiting).\n */\nexport function runRecordOutputSource(\n projectRoot: string,\n options: {\n consumer: string;\n producers: ProducerMap;\n projectName: string;\n env?: Env;\n },\n): OutputSource {\n const { consumer, producers, projectName } = options;\n const env = options.env ?? process.env;\n const siblings = siblingEnvs(projectRoot, env);\n return {\n lookup(ref) {\n const notRunning = `${consumer} needs outputs from host \"${ref.host}\", which is not running. Start it first: ph run ${ref.host} (or run a compound that includes it).`;\n const info = producers.get(ref.host);\n // The producer's outputsSchema: an absent optional field omits the\n // consuming property instead of failing.\n const schema =\n info && !(\"error\" in info) ? info.runner.outputsSchema : undefined;\n const withSchema =\n schema !== undefined && schema !== null ? { schema } : {};\n const standalone: { label: string; outputs: Record<string, unknown> }[] =\n [];\n if (ref.member === undefined && info && !(\"error\" in info)) {\n const probe = probeRun(projectRoot, info.name, projectName, env);\n if (probe.status === \"live\" && probe.record.outputs) {\n return {\n status: \"available\",\n outputs: probe.record.outputs,\n ...withSchema,\n };\n }\n for (const sibling of siblings) {\n const other = probeRun(projectRoot, info.name, projectName, sibling);\n if (other.status === \"live\" && other.record.outputs) {\n standalone.push({\n label: `\"${info.name}\" (pid ${other.record.pid})`,\n outputs: other.record.outputs,\n });\n }\n }\n }\n const members = [env, ...siblings]\n .flatMap((root) => listRunRecords(projectRoot, root))\n .filter(\n (record) =>\n record.members !== undefined &&\n record.projectName === projectName &&\n isPidAlive(record.pid),\n )\n .flatMap((record) =>\n Object.entries(record.members ?? {})\n .filter(\n ([key, member]) =>\n member.host === ref.host &&\n (ref.member === undefined || key === ref.member),\n )\n .map(([key, member]) => ({\n label: `member \"${key}\" of \"${record.host}\"`,\n outputs: member.outputs,\n })),\n );\n const found = [...standalone, ...members];\n if (found.length === 1) {\n return {\n status: \"available\",\n outputs: found[0].outputs,\n ...withSchema,\n };\n }\n if (found.length > 1) {\n return {\n status: \"unavailable\",\n message: `${consumer} needs outputs from host \"${ref.host}\", which runs as ${found.map((m) => m.label).join(\" and \")}; stop all but one, or run ${ref.host} on its own.`,\n };\n }\n return { status: \"unavailable\", message: notRunning };\n },\n };\n}\n\n/** The resolving process's `$env` inputs: its environment plus the\n * always-resolvable built-ins (`userData` honours PH_USER_DATA_DIR). */\nexport function processResolveEnv(\n projectRoot: string,\n env: Readonly<Record<string, string | undefined>> = process.env,\n): Pick<ResolveSources, \"env\" | \"builtins\"> {\n return {\n env,\n builtins: {\n userData: defaultUserDataDir(projectRoot, env),\n projectRoot: path.resolve(projectRoot),\n },\n };\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 { z } from \"zod\";\n\n/**\n * What a server verb returns to its supervisor (typed-host-configs 3.1/3.6):\n * `RunnerHandle<O>`. Consumers read a started host only through `outputs`\n * (and `$output` tokens over them). A verb that returns nothing (one-shot,\n * or self-sustaining) is an empty handle.\n */\nexport interface RunnerHandle<O = Record<string, unknown>> {\n outputs: O;\n /** Resolves when the member is serving. */\n ready: Promise<void>;\n /** Reverse-order compound teardown (and standalone signal handling). */\n shutdown(): Promise<void>;\n}\n\n/** The data half of a handle, validated by the compound. `ready`/`shutdown`\n * are functions and promises, so they are checked as TS fields, not here. */\nexport const runnerHandleSchema = z.looseObject({\n outputs: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type RunnerHandleData = z.infer<typeof runnerHandleSchema>;\n\n/** A verb's return value, normalized: validated data plus the live fields\n * when present. */\nexport interface StartedHandle extends RunnerHandleData {\n outputs: Record<string, unknown>;\n ready?: PromiseLike<unknown>;\n shutdown?: () => unknown;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return isRecord(value) && typeof value.then === \"function\";\n}\n\nfunction isCallable(value: unknown): value is (this: unknown) => unknown {\n return typeof value === \"function\";\n}\n\n/** Normalize what a verb returned. `undefined` (a self-sustaining bridge)\n * is an empty handle; anything else must match runnerHandleSchema. */\nexport function toStartedHandle(value: unknown, where: string): StartedHandle {\n if (value === undefined || value === null) return { outputs: {} };\n const parsed = runnerHandleSchema.safeParse(value);\n if (!parsed.success) {\n throw new Error(\n `${where} returned an invalid runner handle:\\n${z.prettifyError(parsed.error)}`,\n );\n }\n const live = isRecord(value) ? value : {};\n const shutdown = live.shutdown;\n return {\n ...parsed.data,\n outputs: parsed.data.outputs ?? {},\n ...(isPromiseLike(live.ready) ? { ready: live.ready } : {}),\n ...(isCallable(shutdown) ? { shutdown: () => shutdown.call(value) } : {}),\n };\n}\n","import { z } from \"zod\";\nimport {\n declaredGenericCompoundHostSchema,\n type ChildWrapper,\n type CompoundWiring,\n type HostDefinition,\n type RunnerKind,\n} from \"./host-schemas.js\";\nimport { applyChildWrapper, type MemberDraft } from \"./child-wrapper.js\";\nimport { substituteBuiltinEnv } from \"./env-substitution.js\";\nimport { loadHost } from \"./host-loader.js\";\nimport { declaresKey, outputSitesOf } from \"./resolve/declared.js\";\nimport { processResolveEnv, runnerOutputsSchema } from \"./resolve/node.js\";\nimport { memberForRef, planCompound } from \"./resolve/plan.js\";\nimport { findRemovedForms } from \"./resolve/removed-forms.js\";\nimport { isPlainObject } from \"./resolve/walk.js\";\nimport { emptyMaps, resolveHostOutputs } from \"./resolve/resolve.js\";\nimport { compoundOutputSource } from \"./resolve/sources.js\";\nimport {\n clearRunRecord,\n probeRun,\n writeRunRecord,\n type RunRecordMember,\n} from \"./run-record.js\";\nimport { splitCompoundArgv } from \"./runner-args.js\";\nimport { toStartedHandle, type StartedHandle } from \"./runner-handle.js\";\nimport {\n CONNECT_RUNNER,\n getVerb,\n isSchemaLike,\n ONE_SHOT_VERBS,\n resolveRunnerModule,\n RunnerError,\n validateDeclaredHost,\n validateHost,\n type RunnerContext,\n type RunnerModule,\n} from \"./runner-resolver.js\";\n\nexport type { MemberDraft } from \"./child-wrapper.js\";\nexport type { ChildWrapper, CompoundWiring } from \"./host-schemas.js\";\nexport type { RunnerHandle, StartedHandle } from \"./runner-handle.js\";\n\n/**\n * The generic compound runner: supervises the members a compound host\n * declares, each started via its OWN declared runner at its own effective\n * verb, writes a v2 .ph/run/<host>.json record, holds a per-project lock\n * (neither at a one-shot verb such as build, which starts nothing), and\n * tears members down in reverse order through their `shutdown()`.\n *\n * Members consume each other's outputs through `$output` tokens: the\n * dependency plan (resolve/plan.ts) orders the start, each member's tokens\n * resolve against the live outputs of the members started before it, and\n * the member's runner validates the resolved host.\n *\n * Attached and in-process: member verbs start their servers (which hold the\n * event loop) and return a handle; the compound lives as long as they do.\n */\n\ninterface StartedMember {\n name: string;\n member: ChildWrapper;\n specifier: string;\n kind: RunnerKind;\n verb: string;\n handle: StartedHandle;\n /** The outputs consumers read and the record holds: the handle's outputs\n * as parsed by the member runner's outputsSchema. */\n outputs: Record<string, unknown>;\n}\n\nexport interface PreparedMember {\n key: string;\n member: ChildWrapper;\n draft: MemberDraft;\n specifier: string;\n runner: RunnerModule;\n file: string;\n}\n\nexport async function memberDraft(\n projectRoot: string,\n member: ChildWrapper,\n): Promise<MemberDraft> {\n return applyChildWrapper(\n (await loadHost(projectRoot, member.host)).host,\n member,\n );\n}\n\n/** Whether a member receives the compound's `cspRegistrySync` wiring (as\n * `runner.cspRegistrySync`): its runner declares that option (any specifier\n * that reaches the Connect runner), or it names the Connect runner. A\n * member's role is its runner, not its folder. */\nexport function takesCspRegistrySync(m: PreparedMember): boolean {\n return (\n m.specifier === CONNECT_RUNNER ||\n declaresKey(m.runner.hostSchema, [\"runner\"], \"cspRegistrySync\")\n );\n}\n\nexport interface RunCompoundOptions {\n /** Project identity for the lock (defaults read from package.json by the CLI). */\n projectName: string;\n /** Extra record fields (e.g. mcpUrl). */\n recordExtra?: Record<string, unknown>;\n /** Registers the SIGINT/SIGTERM handlers (default true; tests pass false\n * and call `handleSignal`). */\n installSignalHandlers?: boolean;\n /** How the compound exits after a signal (default `process.exit`). */\n exit?: (code: number) => void;\n /** Stops the compound as SIGTERM would, once this delivers anything or\n * ends: see {@link stopStreamOf}. */\n stopStream?: NodeJS.ReadableStream;\n /** How long a stream's stop may take before exiting regardless (default\n * {@link STOP_STREAM_LIMIT_MS}). */\n stopStreamLimitMs?: number;\n /** What a stream's supervisor reads (default stdout and stderr). */\n supervisedOutputs?: readonly NodeJS.WritableStream[];\n}\n\n/** Set by a supervisor that holds this process's stdin. */\nexport const STOP_ON_STDIN_ENV = \"PH_STOP_ON_STDIN\";\n\n/** Past the shell's own limit: this only matters when no shell is left. */\nexport const STOP_STREAM_LIMIT_MS = 15_000;\n\n/**\n * Windows has no SIGTERM, so a supervisor asks a stack to stop through its\n * stdin: a line, or the pipe closing, which also covers the supervisor dying.\n * Only when it asks to: a stack started from a script may have no stdin.\n */\nexport function stopStreamOf(\n env: NodeJS.ProcessEnv,\n stdin: () => NodeJS.ReadableStream,\n): NodeJS.ReadableStream | undefined {\n return env[STOP_ON_STDIN_ENV] === \"1\" ? stdin() : undefined;\n}\n\nfunction whenStreamStops(stream: NodeJS.ReadableStream, stop: () => void) {\n let stopped = false;\n const once = () => {\n if (stopped) return;\n stopped = true;\n stop();\n };\n for (const event of [\"data\", \"end\", \"close\", \"error\"]) {\n stream.once(event, once);\n }\n stream.resume();\n}\n\nexport interface RunCompoundResult {\n started: StartedMember[];\n /** Graceful teardown, consumers before producers (reverse dependency\n * order); memoized. */\n shutdown: () => Promise<void>;\n /** What the compound's signal handlers run: the first signal shuts the\n * members down and exits once (130 / 143); later signals are ignored\n * while that teardown runs. */\n handleSignal: (signal: \"SIGINT\" | \"SIGTERM\") => Promise<void>;\n}\n\n/** The verb the generic compound starts its members at for its own `verb`:\n * `run` follows the compound's defaultVerb. */\nexport function compoundStartVerb(\n verb: string,\n runner: { defaultVerb?: string },\n): string {\n return verb === \"run\" ? (runner.defaultVerb ?? \"run\") : verb;\n}\n\n/** At compound verb \"run\" each member runs its own (merged) defaultVerb —\n * what lets a desktop compound pair a switchboard at `run` with a connect at\n * `serve`. An explicit forwarded verb stays uniform across members. */\nexport function memberVerbOf(\n compoundVerb: string,\n runner: { defaultVerb?: string },\n): string {\n return compoundVerb === \"run\" ? (runner.defaultVerb ?? \"run\") : compoundVerb;\n}\n\nexport async function runCompound(\n hostInput: HostDefinition,\n ctx: RunnerContext,\n options: RunCompoundOptions,\n): Promise<RunCompoundResult> {\n const compoundFile = `hosts/${hostInput.name}`;\n const removed = findRemovedForms(hostInput);\n if (removed.length > 0) {\n throw new RunnerError(\n `${compoundFile}: removed form:\\n${removed.map((r) => ` - ${r.path}: ${r.message}`).join(\"\\n\")}`,\n );\n }\n // Declared form: member wrappers may hold tokens (resolved per member).\n const parsed = declaredGenericCompoundHostSchema.safeParse(hostInput);\n if (!parsed.success) {\n throw new Error(\n `${compoundFile}: invalid compound host:\\n${z.prettifyError(parsed.error)}`,\n );\n }\n const host = parsed.data;\n const projectRoot = ctx.projectRoot;\n const wiring: CompoundWiring = host.config ?? {};\n // Resolved by the calling runner module: its `run` maps to defaultVerb.\n const verb = ctx.verb;\n // A one-shot compound verb (build) starts nothing: no lock, and no record\n // to write or clear (clearing would delete a live instance's record).\n const oneShotCompound = ONE_SHOT_VERBS.has(verb);\n const keepsRecord = wiring.runtimeRecord !== false && !oneShotCompound;\n\n // From the start, so a stop during boot takes effect when boot finishes.\n let stopRequested = false;\n let stopFromStream: () => void = () => {\n stopRequested = true;\n };\n if (options.stopStream && !oneShotCompound) {\n whenStreamStops(options.stopStream, () => stopFromStream());\n // These go when the supervisor does, and with no listener the next log\n // line would be a fatal error in the middle of the shutdown it started.\n const outputs = options.supervisedOutputs ?? [\n process.stdout,\n process.stderr,\n ];\n for (const output of outputs) output.on(\"error\", () => undefined);\n }\n\n // Lock: one live instance per project per host (storage-root contention).\n const probe = oneShotCompound\n ? undefined\n : probeRun(projectRoot, host.name, options.projectName);\n if (probe?.status === \"live\") {\n throw new Error(\n `${host.name} is already running for this project (pid ${probe.record.pid}). ` +\n `Stop it before starting another.`,\n );\n }\n if (probe?.status === \"foreign\") {\n throw new Error(\n `.ph/run/${host.name}.json describes a live \"${probe.record.projectName}\", ` +\n `but this project is \"${options.projectName}\". Refusing to start a second instance.`,\n );\n }\n // stale record: proceed (a dead pid does not hold the lock)\n\n // Declared phase: every member's draft, runner and tokens, before any\n // member starts — a bad token or order fails with nothing running.\n const prepared = await prepareMembers(projectRoot, host.children);\n const plan = planCompound(\n prepared.map((m) => ({\n key: m.key,\n host: m.member.host,\n refs: outputSitesOf(m.draft).map(({ ref, path }) => ({ ref, path })),\n })),\n wiring.startOrder,\n );\n const byKey = new Map(prepared.map((m) => [m.key, m]));\n const members = prepared.map((m) => ({ key: m.key, host: m.member.host }));\n for (const m of prepared) {\n validateDeclaredHost(m.runner, m.specifier, m.draft, m.file, {\n outputsSchemaOf: (ref) => {\n const target = memberForRef(ref, members);\n if (\"error\" in target) return { error: target.error };\n const producer = byKey.get(target.key);\n return producer\n ? runnerOutputsSchema(\n producer.runner,\n producer.specifier,\n `member \"${target.key}\"`,\n )\n : { error: `names member \"${target.key}\", which was not prepared.` };\n },\n });\n }\n\n // This invocation's arguments, per member: one no member accepts fails\n // with nothing running.\n const memberArgv = splitCompoundArgv(\n ctx.argv ?? [],\n hostInput.name,\n prepared.map((m) => ({\n key: m.key,\n runner: m.specifier,\n schema: m.runner.argsSchema,\n })),\n );\n\n if (wiring.cspRegistrySync && !prepared.some(takesCspRegistrySync)) {\n console.warn(\n `${compoundFile}: config.cspRegistrySync is set, but no member's runner declares runner.cspRegistrySync (members run: ${prepared.map((m) => m.specifier).join(\", \")}); the baked Connect CSP is not patched for the runtime registry.`,\n );\n }\n\n const started: StartedMember[] = [];\n const liveOutputs = new Map<string, Record<string, unknown>>();\n const outputs = compoundOutputSource(\n members,\n liveOutputs,\n host.name,\n new Map(prepared.map((m) => [m.key, m.runner.outputsSchema])),\n );\n const resolveEnv = processResolveEnv(projectRoot, ctx.env);\n\n // Members start in plan order (producers first), so the reverse is\n // reverse dependency order: a consumer stops before what it reads.\n let stopping: Promise<void> | undefined;\n const shutdown = () =>\n (stopping ??= (async () => {\n for (const m of [...started].reverse()) {\n try {\n await m.handle.shutdown?.();\n } catch {\n // best effort — keep tearing down the rest\n }\n }\n if (keepsRecord) clearRunRecord(projectRoot, host.name);\n })());\n\n try {\n for (const name of plan.order) {\n const m = byKey.get(name);\n if (!m) continue;\n const memberVerb = memberVerbOf(verb, m.draft.runner);\n const oneShot = ONE_SHOT_VERBS.has(memberVerb);\n // A one-shot member (build) needs no other member's outputs: it gets\n // its declared host with only the \"${userData}\"/\"${projectRoot}\"\n // string sugar substituted (tokens stay; its verb reads paths, never\n // outputs; a $map reaches the verb as an empty collection). Everything\n // else resolves against the members started before it and is\n // validated in resolved form.\n const resolved = oneShot\n ? substituteBuiltinEnv(m.draft, resolveEnv.builtins ?? {})\n : resolveHostOutputs(m.draft, {\n outputs,\n ...resolveEnv,\n where: m.file,\n });\n if (wiring.cspRegistrySync && takesCspRegistrySync(m)) {\n resolved.runner = { ...resolved.runner, cspRegistrySync: true };\n }\n const validated = validateHost(\n m.runner,\n m.specifier,\n resolved,\n m.file,\n oneShot ? { tokens: \"allow\" } : {},\n );\n const fn = getVerb(m.runner, m.specifier, memberVerb);\n const where = `${name} (${m.specifier} ${memberVerb})`;\n const argv = memberArgv.get(name) ?? [];\n const handle = toStartedHandle(\n await fn(oneShot ? emptyMaps(validated, resolved) : validated, {\n projectRoot,\n env: ctx.env,\n verb: memberVerb,\n parent: { host: host.name, verb },\n ...(argv.length > 0 ? { argv } : {}),\n }),\n where,\n );\n // Registered before `ready` settles, so a failed start still tears\n // this member down.\n started.push({\n name,\n member: m.member,\n specifier: m.specifier,\n kind: m.runner.kind,\n verb: memberVerb,\n handle,\n outputs: handle.outputs,\n });\n if (handle.ready) await handle.ready;\n // Consumers and the record see the PARSED outputs (schema defaults,\n // transforms, stripped keys), as a standalone run publishes them.\n let memberOutputs = handle.outputs;\n if (!oneShot && isSchemaLike(m.runner.outputsSchema)) {\n const checked = m.runner.outputsSchema.safeParse(handle.outputs);\n if (!checked.success) {\n throw new Error(\n `${where} reported outputs that fail its outputsSchema:\\n${checked.error.issues.map((i) => ` - ${i.path.map(String).join(\".\") || \"<root>\"}: ${i.message}`).join(\"\\n\")}`,\n );\n }\n if (!isPlainObject(checked.data)) {\n throw new Error(\n `${where}: its outputsSchema parsed the outputs to ${JSON.stringify(checked.data)}, not an object.`,\n );\n }\n memberOutputs = checked.data;\n }\n started[started.length - 1].outputs = memberOutputs;\n liveOutputs.set(name, memberOutputs);\n }\n } catch (error) {\n await shutdown();\n throw error;\n }\n\n if (keepsRecord) {\n const recordMembers: Record<string, RunRecordMember> = {};\n for (const m of started) {\n recordMembers[m.name] = {\n host: m.member.host,\n runnerModule: m.specifier,\n kind: m.kind,\n verb: m.verb,\n outputs: m.outputs,\n };\n }\n writeRunRecord(projectRoot, {\n version: 2,\n host: host.name,\n projectName: options.projectName,\n kind: \"compound\",\n verb,\n pid: process.pid,\n startedAt: new Date().toISOString(),\n members: recordMembers,\n ...(options.recordExtra ? { extra: options.recordExtra } : {}),\n });\n }\n\n // The compound owns the exit: members run without process-exiting signal\n // handlers (ctx.parent is set), so one Ctrl-C reaches only this handler.\n const exit = options.exit ?? ((code: number) => process.exit(code));\n let signalled: Promise<void> | undefined;\n const handleSignal = (signal: \"SIGINT\" | \"SIGTERM\") => {\n if (signalled) return signalled;\n const code = signal === \"SIGINT\" ? 130 : 143;\n signalled = shutdown().finally(() => exit(code));\n return signalled;\n };\n if (options.installSignalHandlers !== false) {\n process.on(\"exit\", () => {\n if (keepsRecord) clearRunRecord(projectRoot, host.name);\n });\n process.on(\"SIGINT\", () => void handleSignal(\"SIGINT\"));\n process.on(\"SIGTERM\", () => void handleSignal(\"SIGTERM\"));\n }\n stopFromStream = () => {\n // No supervisor may be left to end a shutdown that hangs.\n const limit = options.stopStreamLimitMs ?? STOP_STREAM_LIMIT_MS;\n setTimeout(() => exit(143), limit).unref();\n void handleSignal(\"SIGTERM\");\n };\n if (stopRequested) stopFromStream();\n\n return { started, shutdown, handleSignal };\n}\n\n/** Load every member's draft and runner, in declaration order. */\nasync function prepareMembers(\n projectRoot: string,\n children: Record<string, ChildWrapper>,\n): Promise<PreparedMember[]> {\n const out: PreparedMember[] = [];\n for (const [key, member] of Object.entries(children)) {\n out.push(await prepareMember(projectRoot, key, member));\n }\n return out;\n}\n\n/** One member's draft and runner. */\nexport async function prepareMember(\n projectRoot: string,\n key: string,\n member: ChildWrapper,\n): Promise<PreparedMember> {\n const draft = await memberDraft(projectRoot, member);\n const specifier = draft.runner.module;\n return {\n key,\n member,\n draft,\n specifier,\n runner: await resolveRunnerModule(projectRoot, specifier),\n file: `hosts/${member.host}/host.js`,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,IAAa,cAAb,cAAiC,MAAM;CACrC,YAAY,SAAiB,MAAe;EAC1C,MAAM,OAAO,GAAG,QAAQ,YAAY,SAAS,OAAO;EACpD,KAAK,OAAO;CACd;AACF;AAIA,MAAa,0BAA0B,EAAE,aAAa;CACpD,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;;CAExB,SAAS,EAAE,QAAQ,CAAC,CAAC,SAAS;;CAE9B,OAAO,EACJ,MAAM,CAAC,EAAE,QAAQ,GAAG,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAC1D,SAAS;;CAEZ,QAAQ,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;AACrD,CAAC;AAED,MAAa,oBAAoB,EAAE,MAAM,CACvC,EAAE,OAAO,CAAC,CAAC,IA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AC7B;AACF"}
|
|
1
|
+
{"version":3,"file":"compound-DKi56SSx.mjs","names":["factory","valueAt","isRecord","isRecord"],"sources":["../src/plugins.ts","../src/plugins-resolve.ts","../src/drive-schema.ts","../src/host-schemas.ts","../src/resolve/walk.ts","../src/resolve/declared.ts","../src/resolve/removed-forms.ts","../src/env-substitution.ts","../src/resolve/plan.ts","../src/resolve/resolve.ts","../src/runner-resolver.ts","../src/host-loader.ts","../src/runner-args.ts","../src/run-record-schema.ts","../src/run-record.ts","../src/child-wrapper.ts","../src/placeholders.ts","../src/resolve/node.ts","../src/resolve/sources.ts","../src/runner-handle.ts","../src/compound.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/**\n * R1 — the host plugin framework (bridge-runners-to-plugins plan,\n * customization-references/host-core as the blueprint).\n *\n * A plugin is hooks + contributions; hooks are boot wiring (main realm only),\n * contributions are declarative, serializable surface. Host RUNTIMES define\n * the hook vocabulary and interleave their own wiring between stages — they\n * are never plugins themselves.\n *\n * host.js carries the COMPOSITION as `runner.plugins` entries:\n * string | { module, enabled?, verbs?, config? }\n * Presence is activation (enabled defaults true); `verbs` scopes an entry to\n * matching run verbs; `config` is validated against the plugin's declared\n * zod schema. Entries resolve from the PROJECT's dependency tree exactly\n * like runner modules.\n */\n\nexport class PluginError extends Error {\n constructor(message: string, hint?: string) {\n super(hint ? `${message}\\n Hint: ${hint}` : message);\n this.name = \"PluginError\";\n }\n}\n\n/* ------------------------------------------------------------------ entries */\n\nexport const pluginEntryObjectSchema = z.strictObject({\n module: z.string().min(1),\n /** Presence is activation BY DEFAULT; false is the explicit off-switch. */\n enabled: z.boolean().optional(),\n /** \"*\" (default) or the run verbs this entry is active for. */\n verbs: z\n .union([z.literal(\"*\"), z.array(z.string().min(1)).min(1)])\n .optional(),\n /** Validated against the plugin's declared configSchema at resolution. */\n config: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const pluginEntrySchema = z.union([\n z.string().min(1),\n pluginEntryObjectSchema,\n]);\n\n/** The validated (runtime) entry shape. Authors write `PluginEntry`\n * (host-types.ts), which types known plugins' configs. */\nexport type PluginEntryData = z.infer<typeof pluginEntrySchema>;\nexport type { PluginEntry } from \"./host-types.js\";\n\nexport interface NormalizedPluginEntry {\n module: string;\n enabled: boolean;\n verbs: \"*\" | string[];\n config: Record<string, unknown>;\n}\n\nexport function normalizePluginEntry(\n entry: PluginEntryData,\n): NormalizedPluginEntry {\n if (typeof entry === \"string\") {\n return { module: entry, enabled: true, verbs: \"*\", config: {} };\n }\n return {\n module: entry.module,\n enabled: entry.enabled ?? true,\n verbs: entry.verbs ?? \"*\",\n config: entry.config ?? {},\n };\n}\n\n/** Module is the identity key: a duplicate makes override targeting and\n * ordering ambiguous, so it fails loudly. */\nexport function normalizePluginEntries(\n entries: readonly PluginEntryData[],\n where: string,\n): NormalizedPluginEntry[] {\n const normalized = entries.map(normalizePluginEntry);\n const seen = new Set<string>();\n for (const entry of normalized) {\n if (seen.has(entry.module)) {\n throw new PluginError(\n `${where}: plugin \"${entry.module}\" is listed twice.`,\n \"Module specifiers are the identity key of a composition; a plugin meant to run twice needs distinct subpath specifiers.\",\n );\n }\n seen.add(entry.module);\n }\n return normalized;\n}\n\nexport function entryActiveForVerb(\n entry: NormalizedPluginEntry,\n verb: string,\n): boolean {\n if (!entry.enabled) return false;\n return entry.verbs === \"*\" || entry.verbs.includes(verb);\n}\n\n/* ---------------------------------------------------------------- hierarchy */\n\n/**\n * The appliesTo hierarchy. \"reactor\" is the base every reactor host extends;\n * \"compound\" is its own branch (plugins over the member set — e.g. the clint\n * proxy). Host runtimes register their id with a parent; compatibility walks\n * the parent chain.\n */\nconst HOST_TYPE_PARENTS: Record<string, string | null> = {\n reactor: null,\n compound: null,\n connect: \"reactor\",\n switchboard: \"reactor\",\n mastra: \"reactor\",\n};\n\nexport function registerHostType(id: string, parent: string | null): void {\n if (id in HOST_TYPE_PARENTS && HOST_TYPE_PARENTS[id] !== parent) {\n throw new PluginError(\n `Host type \"${id}\" is already registered with parent \"${String(HOST_TYPE_PARENTS[id])}\".`,\n );\n }\n HOST_TYPE_PARENTS[id] = parent;\n}\n\nexport function hostTypeSatisfies(\n hostType: string,\n appliesTo: string,\n): boolean {\n let current: string | null = hostType;\n while (current !== null) {\n if (current === appliesTo) return true;\n current = current in HOST_TYPE_PARENTS ? HOST_TYPE_PARENTS[current] : null;\n }\n return false;\n}\n\n/* ------------------------------------------------------------------- plugin */\n\n/** Hook kinds (v1 §2.2). The hook VOCABULARY is defined by host runtimes;\n * plugins implement subsets of it. */\nexport type Provide<T, C> = (ctx: C) => T | Promise<T>;\nexport type Transform<T, C> = (value: T, ctx: C) => T | Promise<T>;\nexport type Observe<C> = (ctx: C) => void | Promise<void>;\n\n/**\n * Core contributions — declarative, serializable, realm-crossing. Host\n * runtimes extend this with their own kinds (UI slots live in connect-host,\n * never here). `drives` entries use the drive declaration shape from\n * drives.ts; kept as unknown here to avoid a cycle — the merge is shape-blind.\n */\nexport interface Contributions {\n drives?: unknown[];\n packages?: string[];\n configDeclarations?: { name: string; type?: string; description?: string }[];\n [kind: string]: unknown[] | undefined;\n}\n\nexport interface HostPlugin<\n THooks = Record<string, unknown>,\n TConfig = unknown,\n> {\n /** Stable id; used in ordering, dependsOn, and every diagnostic. */\n name: string;\n /** Host-type requirement; the entry is rejected on a host outside the\n * hierarchy branch. Default: \"reactor\". */\n appliesTo?: string;\n /** Coarse ordering bucket (Vite-style). Default: \"normal\". */\n enforce?: \"pre\" | \"post\";\n /** Hard dependencies on OTHER PLUGINS — the host runtime is implied and\n * never named. Missing dependency or cycle fails boot naming both sides. */\n dependsOn?: string[];\n /** Declared config shape; entry config is validated against it. A plugin\n * without a schema accepts no config (passing one is a boot error). */\n configSchema?: z.ZodType<TConfig>;\n hooks?: Partial<THooks>;\n contributions?: Contributions;\n}\n\n/** A plugin module default-exports either a HostPlugin object (no config\n * accepted) or a factory `(config) => HostPlugin`. */\nexport type HostPluginModule<\n THooks = Record<string, unknown>,\n TConfig = unknown,\n> =\n | HostPlugin<THooks, TConfig>\n | ((config: TConfig) => HostPlugin<THooks, TConfig>);\n\nexport interface ResolvedPlugin<THooks = Record<string, unknown>> {\n entry: NormalizedPluginEntry;\n plugin: HostPlugin<THooks>;\n /** Provenance for contribution merge ordering. */\n provenance: \"built-in\" | \"local\" | \"dependency\";\n}\n\n/* ----------------------------------------------------------------- ordering */\n\n/** Registration order, bucketed pre → normal → post (stable within buckets),\n * then dependsOn topo-sorted within the bucketed order. */\nexport function resolveOrder<THooks>(\n plugins: readonly HostPlugin<THooks>[],\n): HostPlugin<THooks>[] {\n const buckets: Record<\"pre\" | \"normal\" | \"post\", HostPlugin<THooks>[]> = {\n pre: [],\n normal: [],\n post: [],\n };\n for (const plugin of plugins)\n buckets[plugin.enforce ?? \"normal\"].push(plugin);\n const bucketed = [...buckets.pre, ...buckets.normal, ...buckets.post];\n\n const byName = new Map(bucketed.map((p) => [p.name, p]));\n for (const plugin of bucketed) {\n for (const dep of plugin.dependsOn ?? []) {\n if (!byName.has(dep)) {\n throw new PluginError(\n `Plugin \"${plugin.name}\" depends on missing plugin \"${dep}\".`,\n \"dependsOn names PLUGINS only — the host runtime is implied and never named.\",\n );\n }\n }\n }\n\n const ordered: HostPlugin<THooks>[] = [];\n const state = new Map<string, \"visiting\" | \"done\">();\n const visit = (plugin: HostPlugin<THooks>, chain: string[]): void => {\n const mark = state.get(plugin.name);\n if (mark === \"done\") return;\n if (mark === \"visiting\") {\n throw new PluginError(\n `Plugin dependency cycle: ${[...chain, plugin.name].join(\" -> \")}.`,\n );\n }\n state.set(plugin.name, \"visiting\");\n for (const dep of plugin.dependsOn ?? []) {\n visit(byName.get(dep)!, [...chain, plugin.name]);\n }\n state.set(plugin.name, \"done\");\n ordered.push(plugin);\n };\n for (const plugin of bucketed) visit(plugin, []);\n return ordered;\n}\n\n/* -------------------------------------------------------------------- hooks */\n\nexport async function runProvideHook<T, C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n): Promise<T | undefined> {\n const impls = plugins.filter((p) => typeof p.hooks?.[name] === \"function\");\n if (impls.length > 1) {\n throw new PluginError(\n `Hook \"${name}\" is provided by ${impls.map((p) => `\"${p.name}\"`).join(\" and \")} — provide hooks have one winner.`,\n );\n }\n const impl = impls[0]?.hooks?.[name] as Provide<T, C> | undefined;\n return impl ? await impl(ctx) : undefined;\n}\n\nexport async function runTransformHook<T, C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n seed: T,\n): Promise<T> {\n let value = seed;\n for (const plugin of plugins) {\n const impl = plugin.hooks?.[name] as Transform<T, C> | undefined;\n if (typeof impl === \"function\") value = await impl(value, ctx);\n }\n return value;\n}\n\n/** Sequential observe, in plugin order — for lifecycle moments whose order\n * is load-bearing (teardown: the switchboard stops privacy before workflows\n * before the api, per the carve map). */\nexport async function runObserveHookSequential<C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n): Promise<void> {\n for (const plugin of plugins) {\n const impl = plugin.hooks?.[name] as Observe<C> | undefined;\n if (typeof impl === \"function\") await impl(ctx);\n }\n}\n\nexport async function runObserveHook<C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n): Promise<void> {\n await Promise.all(\n plugins.map(async (plugin) => {\n const impl = plugin.hooks?.[name] as Observe<C> | undefined;\n if (typeof impl === \"function\") await impl(ctx);\n }),\n );\n}\n\n/* ------------------------------------------------------------ contributions */\n\nexport interface ContributionSource {\n pluginName: string;\n provenance: \"built-in\" | \"local\" | \"dependency\";\n}\n\nexport interface MergedContribution<T = unknown> {\n value: T;\n source: ContributionSource;\n}\n\n/** Array kinds concatenate in provenance-then-order sequence (built-in first,\n * so later sources read as overrides where consumers want last-wins). */\nexport function mergeContributions(\n resolved: readonly {\n plugin: HostPlugin;\n provenance: ContributionSource[\"provenance\"];\n }[],\n): Record<string, MergedContribution[]> {\n const rank: Record<ContributionSource[\"provenance\"], number> = {\n \"built-in\": 0,\n local: 1,\n dependency: 2,\n };\n const sorted = [...resolved].sort(\n (a, b) => rank[a.provenance] - rank[b.provenance],\n );\n const merged: Record<string, MergedContribution[]> = {};\n for (const { plugin, provenance } of sorted) {\n for (const [kind, values] of Object.entries(plugin.contributions ?? {})) {\n if (!values) continue;\n const bucket = (merged[kind] ??= []);\n for (const value of values) {\n bucket.push({ value, source: { pluginName: plugin.name, provenance } });\n }\n }\n }\n return merged;\n}\n","import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { z } from \"zod\";\nimport {\n entryActiveForVerb,\n hostTypeSatisfies,\n normalizePluginEntries,\n PluginError,\n type HostPlugin,\n type PluginEntryData,\n type ResolvedPlugin,\n} from \"./plugins.js\";\n\n/**\n * NODE-ONLY plugin resolution (split from plugins.ts so the pure runner core\n * stays browser-safe for ConnectCore — R3). Resolves host.js entries from the\n * PROJECT dependency tree, exactly like runner modules.\n */\n\nfunction isHostPluginShape(value: unknown): value is HostPlugin {\n return (\n value !== null &&\n typeof value === \"object\" &&\n typeof (value as HostPlugin).name === \"string\"\n );\n}\n\n/**\n * Resolve host.js plugin entries into live plugins for one host boot:\n * verb-filter → module resolution from the project tree (default condition,\n * like runners) → factory/object contract → config validation → appliesTo.\n */\nexport async function resolveHostPlugins<THooks = Record<string, unknown>>(\n projectRoot: string,\n hostType: string,\n verb: string,\n entries: readonly PluginEntryData[],\n where: string,\n): Promise<ResolvedPlugin<THooks>[]> {\n const normalized = normalizePluginEntries(entries, where);\n const projectRequire = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n\n const resolved: ResolvedPlugin<THooks>[] = [];\n for (const entry of normalized) {\n if (!entryActiveForVerb(entry, verb)) continue;\n\n let file: string;\n try {\n file = projectRequire.resolve(entry.module);\n } catch {\n throw new PluginError(\n `${where}: cannot resolve plugin \"${entry.module}\" from ${projectRoot}.`,\n \"Plugins resolve from the project dependency tree, exactly like runner modules.\",\n );\n }\n const module = (await import(pathToFileURL(file).href)) as {\n default?: unknown;\n };\n const exported = module.default;\n\n let plugin: HostPlugin<THooks>;\n if (typeof exported === \"function\") {\n const factory = exported as (config: unknown) => HostPlugin<THooks>;\n plugin = factory(entry.config);\n } else if (isHostPluginShape(exported)) {\n if (Object.keys(entry.config).length > 0 && !exported.configSchema) {\n throw new PluginError(\n `${where}: plugin \"${entry.module}\" takes no config, but the entry passes one.`,\n );\n }\n plugin = exported as HostPlugin<THooks>;\n } else {\n throw new PluginError(\n `${where}: \"${entry.module}\" does not default-export a plugin object or factory.`,\n \"Export `{ name, hooks?, contributions? }` or `(config) => plugin`.\",\n );\n }\n\n if (plugin.configSchema) {\n const parsed = plugin.configSchema.safeParse(entry.config);\n if (!parsed.success) {\n throw new PluginError(\n `${where}: config for plugin \"${plugin.name}\" is invalid:\\n` +\n z.prettifyError(parsed.error),\n );\n }\n }\n\n const appliesTo = plugin.appliesTo ?? \"reactor\";\n if (!hostTypeSatisfies(hostType, appliesTo)) {\n throw new PluginError(\n `${where}: plugin \"${plugin.name}\" applies to \"${appliesTo}\" hosts, but this host is \"${hostType}\".`,\n );\n }\n\n resolved.push({ entry, plugin, provenance: \"dependency\" });\n }\n return resolved;\n}\n\n/** A drive a plugin contributes: its declaration (drives.ts shape, validated\n * by the consumer) and the plugin it came from. */\nexport interface ContributedDrive {\n declaration: Record<string, unknown>;\n source: string;\n}\n\nexport interface PluginContributionsPlan {\n drives: ContributedDrive[];\n /** Entries whose module the project tree cannot resolve (e.g. Connect's\n * browser built-ins, which have no Node-resolvable identity module). */\n unresolved: string[];\n}\n\n/**\n * LENIENT resolution for diagnostics (`ph run <host> --explain drives`):\n * collects the drive contributions of the entries active for `verb`. Unlike\n * resolveHostPlugins it does not know the host type (so appliesTo is not\n * checked) and does not fail on a specifier the project tree cannot resolve\n * — the entry is listed under `unresolved` instead. Config is still validated\n * against the plugin's schema, so a bad entry surfaces here too.\n */\nexport async function resolvePluginContributions(\n projectRoot: string,\n verb: string,\n entries: readonly PluginEntryData[],\n where: string,\n): Promise<PluginContributionsPlan> {\n const normalized = normalizePluginEntries(entries, where);\n const projectRequire = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n const plan: PluginContributionsPlan = { drives: [], unresolved: [] };\n for (const entry of normalized) {\n if (!entryActiveForVerb(entry, verb)) continue;\n let file: string;\n try {\n file = projectRequire.resolve(entry.module);\n } catch {\n plan.unresolved.push(entry.module);\n continue;\n }\n const module = (await import(pathToFileURL(file).href)) as {\n default?: unknown;\n };\n const exported = module.default;\n let plugin: HostPlugin;\n if (typeof exported === \"function\") {\n plugin = (exported as (config: unknown) => HostPlugin)(entry.config);\n } else if (isHostPluginShape(exported)) {\n plugin = exported;\n } else {\n plan.unresolved.push(entry.module);\n continue;\n }\n if (plugin.configSchema) {\n const parsed = plugin.configSchema.safeParse(entry.config);\n if (!parsed.success) {\n throw new PluginError(\n `${where}: config for plugin \"${plugin.name}\" is invalid:\\n` +\n z.prettifyError(parsed.error),\n );\n }\n }\n for (const declaration of plugin.contributions?.drives ?? []) {\n plan.drives.push({\n declaration: declaration as Record<string, unknown>,\n source: plugin.name,\n });\n }\n }\n return plan;\n}\n\n/* -------------------------------------------------------------- dead config */\n\n/** One Connect config value a built-in Connect plugin owns. */\nexport interface OwnedConfigSlice {\n /** Dot path inside the connect config block, e.g. \"drives.allowAddDrive\". */\n path: string;\n /** What Connect serves at `path` while the owning plugin is absent from a\n * declared composition (apps/connect plugin-host.ts zeroAbsentSlices). */\n absent: unknown;\n /** The owning plugin's entry config key that sets this value, when the\n * plugin takes it as config; omitted where presence alone is the switch. */\n entryKey?: string;\n}\n\nexport interface ConnectPluginSlices {\n slices: OwnedConfigSlice[];\n /** A slice whose unset or `absent` value leaves every slice of this plugin\n * inert (OpenPanel tracking does nothing without a clientId), so nothing\n * of it is reported as dead. */\n inertUnless?: string;\n}\n\n/**\n * The connect config slices each built-in Connect plugin owns, by specifier\n * (typed-host-configs 1.6). Under a declared composition Connect zeroes a\n * slice whose plugin is absent — presence is activation — so an authored\n * value there is dead config. Connect's built-ins are browser modules with no\n * Node-resolvable identity, so their ownership is declared here as data; a\n * Connect test pins it to plugin-host's zeroing.\n */\nexport const CONNECT_PLUGIN_OWNED_SLICES: Readonly<\n Record<string, ConnectPluginSlices>\n> = {\n \"@powerhousedao/connect/plugins/generic\": {\n slices: [\n {\n path: \"drives.allowAddDrive\",\n absent: false,\n entryKey: \"allowAddDrive\",\n },\n {\n path: \"drives.sections\",\n absent: {\n remote: { enabled: false, allowAdd: false, allowDelete: false },\n local: { enabled: false, allowAdd: false, allowDelete: false },\n },\n entryKey: \"sections\",\n },\n { path: \"drives.icons\", absent: null, entryKey: \"icons\" },\n { path: \"home.background\", absent: null, entryKey: \"homeBackground\" },\n ],\n },\n \"@powerhousedao/connect/plugins/sentry\": {\n slices: [{ path: \"sentry.dsn\", absent: null, entryKey: \"dsn\" }],\n },\n \"@powerhousedao/connect/plugins/openpanel\": {\n slices: [\n { path: \"openPanel.clientId\", absent: \"\", entryKey: \"clientId\" },\n {\n path: \"openPanel.trackUiEvents\",\n absent: false,\n entryKey: \"trackUiEvents\",\n },\n {\n path: \"openPanel.trackOperations\",\n absent: false,\n entryKey: \"trackOperations\",\n },\n ],\n inertUnless: \"openPanel.clientId\",\n },\n \"@powerhousedao/connect/plugins/assistant\": {\n slices: [{ path: \"ai.assistantEnabled\", absent: false }],\n },\n \"@powerhousedao/vetra-studio/connect\": {\n slices: [{ path: \"app.studioMode\", absent: false }],\n },\n \"@powerhousedao/connect/plugins/workflows\": {\n slices: [{ path: \"app.workflowsEnabled\", absent: false }],\n },\n};\n\nexport interface DeadConfigWarning {\n /** Dot path inside the connect config block. */\n path: string;\n /** The authored value. */\n value: unknown;\n /** What Connect serves instead. */\n served: unknown;\n /** The specifier of the plugin that owns the slice. */\n owner: string;\n message: string;\n}\n\nfunction valueAt(root: unknown, dotted: string): unknown {\n let current = root;\n for (const key of dotted.split(\".\")) {\n if (current === null || typeof current !== \"object\") return undefined;\n current = (current as Record<string, unknown>)[key];\n }\n return current;\n}\n\n/** Whether Connect already serves what the author wrote: every authored leaf\n * equals the served one. An unset leaf asks for nothing, so a partial object\n * (`sections: { remote: { enabled: false } }`) is satisfied by the zeroed\n * slice. */\nfunction alreadyServed(authored: unknown, served: unknown): boolean {\n if (authored === undefined || Object.is(authored, served)) return true;\n if (\n authored === null ||\n served === null ||\n typeof authored !== \"object\" ||\n typeof served !== \"object\" ||\n Array.isArray(authored) !== Array.isArray(served)\n ) {\n return false;\n }\n if (\n Array.isArray(authored) &&\n authored.length !== (served as unknown[]).length\n ) {\n return false;\n }\n const want = authored as Record<string, unknown>;\n const have = served as Record<string, unknown>;\n return Object.keys(want).every((key) => alreadyServed(want[key], have[key]));\n}\n\n/**\n * The composition that serves `config` as Connect serves it with none, for a\n * host that declares no `runner.plugins`. `config` is the connect block\n * Connect would be served without a composition.\n *\n * A built-in configured through its entry is always in it, its entry holding\n * the values `config` has at the slices it owns: composed in, the plugin\n * serves those values again (an unset one falls back to the same default).\n * A built-in whose presence is its switch is in it only where `config`\n * already has that switch on, since composing it in would turn it on.\n */\nexport function defaultConnectComposition(\n config: Record<string, unknown> | undefined,\n): { module: string; config: Record<string, unknown> }[] {\n const composition: { module: string; config: Record<string, unknown> }[] = [];\n for (const [module, { slices }] of Object.entries(\n CONNECT_PLUGIN_OWNED_SLICES,\n )) {\n const entry: Record<string, unknown> = {};\n let configured = false;\n let switchedOn = false;\n for (const { path: slicePath, absent, entryKey } of slices) {\n const value = valueAt(config, slicePath);\n if (entryKey === undefined) {\n switchedOn ||= !alreadyServed(value, absent);\n continue;\n }\n configured = true;\n if (value !== undefined && value !== null) entry[entryKey] = value;\n }\n if (configured || switchedOn) composition.push({ module, config: entry });\n }\n return composition;\n}\n\n/**\n * Dead-config warnings for a Connect host (typed-host-configs 1.6): an\n * authored connect config value whose owning plugin is not in the\n * composition active for `verb`. Connect zeroes such a slice, so the value\n * has no effect — e.g. Sektar's `connect.drives.allowAddDrive: true` without\n * the generic plugin.\n *\n * Nothing is reported when the host declares no composition\n * (`runner.plugins` absent: the classic boot serves the config as is), or\n * when Connect already serves every leaf of the authored value. Warnings, not\n * errors: the host still boots, it just does not do what the value says.\n */\nexport function findDeadConnectConfig(\n config: Record<string, unknown> | undefined,\n entries: readonly PluginEntryData[] | undefined,\n verb: string,\n where: string,\n): DeadConfigWarning[] {\n if (!config || entries === undefined) return [];\n const active = new Set(\n normalizePluginEntries(entries, where)\n .filter((entry) => entryActiveForVerb(entry, verb))\n .map((entry) => entry.module),\n );\n const warnings: DeadConfigWarning[] = [];\n for (const [owner, { slices, inertUnless }] of Object.entries(\n CONNECT_PLUGIN_OWNED_SLICES,\n )) {\n if (active.has(owner)) continue;\n if (inertUnless !== undefined) {\n const gate = slices.find((slice) => slice.path === inertUnless);\n const gateValue = valueAt(config, inertUnless);\n if (alreadyServed(gateValue, gate?.absent)) {\n continue;\n }\n }\n for (const { path: slicePath, absent, entryKey } of slices) {\n const value = valueAt(config, slicePath);\n if (alreadyServed(value, absent)) continue;\n const move =\n entryKey === undefined\n ? `compose \"${owner}\" (presence is the switch)`\n : `compose \"${owner}\" and set \\`${entryKey}\\` in its entry config`;\n warnings.push({\n path: slicePath,\n value,\n served: absent,\n owner,\n message:\n `${where}: config.${slicePath} is dead config: it is owned by plugin \"${owner}\", ` +\n `which this host does not compose for verb \"${verb}\", so Connect serves ${JSON.stringify(absent)} instead of ${JSON.stringify(value)}.` +\n `\\n Hint: ${move}, or delete the value.`,\n });\n }\n }\n return warnings;\n}\n","import { z } from \"zod\";\nimport { tokenable, type TokenableSchema } from \"./tokens.js\";\n\n/**\n * The schema half of drives.ts, zod only so `./schema` stays neutral.\n * - slug: the SEEDING KEY (idempotence); id optional (stable identity).\n * - preferredEditor: stored at header.meta.preferredEditor; Connect config's\n * `app` is the legacy alias.\n * - remote.url: a drive served elsewhere; local fields are ignored for it.\n * Token-able (`$output` on a producer's `drives.<slug>.url`).\n */\nexport function buildDriveDeclarationSchema(\n urlField: (schema: z.ZodString) => TokenableSchema<z.ZodString>,\n) {\n return z.strictObject({\n slug: z.string().min(1),\n id: z.string().min(1).optional(),\n /** Derive the id from the project path, like generateProjectDriveId — the\n * same ids classic `ph vetra` produces. `true` serves the drive under the\n * hashed slug too (the vetra drive's slug IS its hashed id); `\"id\"` hashes\n * only the id and keeps the declared slug (the classic Workflows drive:\n * `/d/workflows`, id `workflows-<hash>`). */\n projectHash: z.union([z.boolean(), z.literal(\"id\")]).optional(),\n /** What a missing drive is created as. Default powerhouse/document-drive. */\n documentType: z\n .enum([\"powerhouse/document-drive\", \"powerhouse/reactor-drive\"])\n .optional(),\n name: z.string().min(1).optional(),\n icon: z.string().optional(),\n preferredEditor: z.string().optional(),\n sharingType: z.enum([\"public\", \"private\", \"shared\"]).optional(),\n availableOffline: z.boolean().optional(),\n remote: z.strictObject({ url: urlField(z.string().min(1)) }).optional(),\n });\n}\n\nexport const driveDeclarationSchema = buildDriveDeclarationSchema(tokenable);\n\nexport type DriveDeclaration = z.infer<typeof driveDeclarationSchema>;\n\nexport const drivesSchema = z.array(driveDeclarationSchema);\n\n/** The project-hashed drive id (`${slug}-${sha256(projectRoot)[0..8]}`) with\n * the hash function injected, so neutral consumers (a browser monitor) can\n * pass `crypto.subtle`-derived or precomputed hex. drives.ts binds it to\n * node:crypto as `projectDriveId`. */\nexport function projectDriveIdWith(\n sha256Hex: (input: string) => string,\n projectRoot: string,\n slug: string,\n): string {\n return `${slug}-${sha256Hex(projectRoot).substring(0, 8)}`;\n}\n","import { switchboardOfDrive } from \"@powerhousedao/shared/host-tokens\";\nimport { isOriginPlaceholderUrl } from \"@powerhousedao/shared/connect/origin-placeholder\";\nimport { z } from \"zod\";\nimport { buildDriveDeclarationSchema } from \"./drive-schema.js\";\nimport { pluginEntrySchema } from \"./plugins.js\";\nimport {\n envTokenable,\n tokenable,\n type EnvToken,\n type TokenableSchema,\n type TokenMode,\n} from \"./tokens.js\";\n\n/**\n * The zod single source for host.js blocks (typed-host-configs G1). Every\n * host type is z.input/z.output of these schemas; nothing is hand-mirrored.\n * Top-level host objects and the `reactor` block are STRICT (a typo fails);\n * `runner` stays loose until each runner declares its options (T2), and\n * `config` is runner-defined.\n *\n * Token-able fields (typed-host-configs 3.5): `reactor.backends.*.remote.url`\n * (required, a switchboard drive address), `reactor.drives` (whole list, e.g. `$map`),\n * `reactor.drives[].remote.url` and `storage.dataDir` (`$env` only). Their z.input admits tokens, their z.output is the resolved type.\n */\n\n/** A host's `name` keys its run record, `.ph/run/<name>.json`, so it must be\n * one safe path segment. */\nexport const HOST_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\nexport const HOST_NAME_MAX_LENGTH = 128;\nexport const HOST_NAME_MESSAGE =\n \"A host name is used as a file name, so use only letters, digits, '.', '_' and '-', start with a letter or digit, and keep it to 128 characters.\";\nexport const hostNameSchema = z\n .string()\n .min(1)\n .max(HOST_NAME_MAX_LENGTH, HOST_NAME_MESSAGE)\n .regex(HOST_NAME_PATTERN, HOST_NAME_MESSAGE);\n\n/**\n * A URL, or one written against the page origin (`${origin}/graphql`): the\n * browser resolves the placeholder when it loads Connect's config, for a\n * member whose own server proxies the switchboard's paths.\n */\nexport const originOrUrlSchema = z.union([\n z.url(),\n z.string().refine(isOriginPlaceholderUrl, {\n message: \"a URL, or ${origin}/<path> for a proxied sibling\",\n }),\n]);\n\nexport const profileSchema = z.strictObject({\n appId: z.string().min(1).optional(),\n name: z.string().min(1).optional(),\n description: z.string().optional(),\n icon: z.string().optional(),\n});\n\nexport const reactorProtocolSchema = z.strictObject({\n featureFlags: z\n .strictObject({\n documentDecisions: z.boolean().optional(),\n authEnforcement: z.boolean().optional(),\n authGroups: z.boolean().optional(),\n authConditions: z.boolean().optional(),\n undoV3: z.boolean().optional(),\n })\n .optional(),\n createSignaturePolicy: z.enum([\"legacy\", \"v2-required\"]).optional(),\n unsupportedStoredDocuments: z.enum([\"refuse\", \"read-only\"]).optional(),\n});\n\nexport const runnerKindSchema = z.enum([\"reactor\", \"compound\"]);\nexport type RunnerKind = z.infer<typeof runnerKindSchema>;\n\nexport const reactorBackendKindSchema = z.enum([\n \"in-process\",\n \"worker\",\n \"remote\",\n]);\n\n// Path-equality for the one-dir guard: pure string normalisation (the host\n// core stays Node-free); the server repeats the check with path.resolve.\nconst samePath = (a: string, b: string): boolean => {\n const norm = (p: string) =>\n p.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\").replace(/^\\.\\//, \"\");\n return norm(a) === norm(b);\n};\n\n/** Compound wiring: the generic compound runner's `config` block.\n * (`projectDrivesIntoConnect` and `drivesPublicBase` were removed in T3: a\n * member consumes another member's drives through `$output` tokens.) */\nexport const compoundWiringSchema = z.strictObject({\n /** Member start order; must name declared children and agree with the\n * output-token dependencies (resolve/plan.ts). Optional: without it the\n * order is derived from the tokens. Unnamed members start after the named\n * ones, in declaration order. */\n startOrder: z.array(z.string().min(1)).optional(),\n /** Write .ph/run/<host>.json (default true). */\n runtimeRecord: z.boolean().optional(),\n /** Patch the baked CSP for the runtime registry on a served Connect\n * member (forwarded as `runner.cspRegistrySync` to every member whose\n * runner is `@powerhousedao/ph-cli/runners/connect`). */\n cspRegistrySync: z.boolean().optional(),\n});\n\n/** `config.startOrder ⊆ keys(children)`, checked where both are visible.\n * Apply it LAST (`.superRefine(refineStartOrder)`) to a runner's final host\n * schema: zod refuses to `.extend()` a refined object. */\nexport function refineStartOrder(\n host: { children: Record<string, unknown>; config?: Record<string, unknown> },\n ctx: z.RefinementCtx,\n): void {\n const startOrder = host.config?.startOrder;\n if (!Array.isArray(startOrder)) return;\n const members = Object.keys(host.children);\n startOrder.forEach((name: unknown, index) => {\n if (startOrder.indexOf(name) !== index) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"config\", \"startOrder\", index],\n message: `startOrder names \"${String(name)}\" twice; each member starts once.`,\n });\n return;\n }\n if (typeof name === \"string\" && members.includes(name)) return;\n ctx.addIssue({\n code: \"custom\",\n path: [\"config\", \"startOrder\", index],\n message: `startOrder names \"${String(name)}\", which is not a member. Members: ${members.join(\", \") || \"(none)\"}.`,\n });\n });\n}\n\n/** How a schema set wraps its token-able fields. Both modes share one static\n * type (declared input, resolved output); they differ at runtime only. */\ninterface FieldWrappers {\n any: <S extends z.ZodType>(schema: S) => TokenableSchema<S>;\n env: <S extends z.ZodType>(schema: S) => TokenableSchema<S, EnvToken>;\n}\n\nconst ALLOW_TOKENS: FieldWrappers = { any: tokenable, env: envTokenable };\n// A one-option union: the same validation as `schema`, typed like the\n// \"allow\" wrappers so both modes share HostSchemas.\nconst FORBID_TOKENS: FieldWrappers = {\n any: (schema) => z.union([schema]),\n env: (schema) => z.union([schema]),\n};\n\n/** The replacement a non-drive `remote.url` message names. */\nfunction useDriveUrl(host = \"switchboard\", member?: string): string {\n const memberPart = member ? `, member: \"${member}\"` : \"\";\n return (\n `remote: { url: ${host}.drives.<slug>.url } with ${host} from ../${host}/outputs.js, ` +\n `or remote: { url: { $output: { host: \"${host}\"${memberPart}, path: [\"drives\", \"<slug>\", \"url\"] } } }`\n );\n}\n\n/** The `$output` of a declared `remote.url` that reads `endpoints.graphql`. */\nfunction endpointsGraphqlRef(\n url: unknown,\n): { host: string; member?: string } | undefined {\n if (typeof url !== \"object\" || url === null || !(\"$output\" in url)) {\n return undefined;\n }\n const ref = (url as { $output: unknown }).$output;\n if (typeof ref !== \"object\" || ref === null) return undefined;\n const { host, member, path } = ref as Record<string, unknown>;\n if (typeof host !== \"string\" || !Array.isArray(path)) return undefined;\n if (path.join(\".\") !== \"endpoints.graphql\") return undefined;\n return { host, ...(typeof member === \"string\" ? { member } : {}) };\n}\n\n/** The slug a drive link names: a `drives.<slug>.url` token's slug or a\n * literal address's served slug; undefined when only runtime knows it. */\nfunction linkedSlug(url: unknown): string | undefined {\n if (typeof url === \"string\") return switchboardOfDrive(url)?.slug;\n const ref =\n typeof url === \"object\" && url !== null && \"$output\" in url\n ? (url as { $output: { path?: unknown } }).$output\n : undefined;\n const path = Array.isArray(ref?.path) ? (ref.path as unknown[]) : [];\n return path.length === 3 &&\n path[0] === \"drives\" &&\n typeof path[1] === \"string\" &&\n path[2] === \"url\"\n ? path[1]\n : undefined;\n}\n\ninterface DeclaredReactorHost {\n runner?: { plugins?: unknown };\n config?: unknown;\n reactor?: {\n backends?: Record<string, { kind: string; remote?: { url: unknown } }>;\n placement?: {\n primary?: string;\n drives?: Record<string, string>;\n newDrives?: string;\n };\n drives?: unknown;\n };\n}\n\n/** The drives a declared host names (home drives, `reactor.drives`, plugin\n * `config.drive` links), or undefined when one is known only at runtime. */\nfunction knownDriveSlugs(host: DeclaredReactorHost): string[] | undefined {\n const reactor = host.reactor ?? {};\n const slugs: string[] = [];\n for (const backend of Object.values(reactor.backends ?? {})) {\n if (backend.kind !== \"remote\") continue;\n const slug = linkedSlug(backend.remote?.url);\n if (slug === undefined) return undefined;\n slugs.push(slug);\n }\n if (reactor.drives !== undefined) {\n if (!Array.isArray(reactor.drives)) return undefined;\n for (const drive of reactor.drives as { slug?: unknown }[]) {\n if (typeof drive.slug === \"string\") slugs.push(drive.slug);\n }\n }\n const plugins = Array.isArray(host.runner?.plugins)\n ? (host.runner.plugins as unknown[])\n : [];\n for (const entry of plugins) {\n const config =\n typeof entry === \"object\" && entry !== null && \"config\" in entry\n ? (entry as { config: unknown }).config\n : undefined;\n if (typeof config !== \"object\" || config === null) continue;\n if (!(\"drive\" in config) || config.drive === undefined) continue;\n const slug = linkedSlug(config.drive);\n if (slug === undefined) return undefined;\n slugs.push(slug);\n }\n for (const drive of connectDefaultDrives(host.config)) {\n if (typeof drive !== \"object\" || drive === null || !(\"url\" in drive)) {\n continue;\n }\n const slug = linkedSlug(drive.url);\n if (slug === undefined) return undefined;\n slugs.push(slug);\n }\n return slugs;\n}\n\n/** A Connect host's `config.drives.defaultDrives`, unchecked. */\nfunction connectDefaultDrives(config: unknown): unknown[] {\n const drives =\n typeof config === \"object\" && config !== null && \"drives\" in config\n ? (config as { drives: unknown }).drives\n : undefined;\n const list =\n typeof drives === \"object\" && drives !== null && \"defaultDrives\" in drives\n ? (drives as { defaultDrives: unknown }).defaultDrives\n : undefined;\n return Array.isArray(list) ? list : [];\n}\n\n/** Declared form, at host level so plugin drives are seen: a placement key\n * must name a drive the host names, when every drive is knowable. A host\n * with no remote backend is not checked: its plugins may contribute drives\n * (a switchboard's workflows drive) that no field names. */\nfunction refineDeclaredPlacementKeys(\n host: DeclaredReactorHost,\n ctx: z.RefinementCtx,\n): void {\n const placed = Object.keys(host.reactor?.placement?.drives ?? {});\n if (placed.length === 0) return;\n const remote = Object.values(host.reactor?.backends ?? {}).some(\n (b) => b.kind === \"remote\",\n );\n if (!remote) return;\n const known = knownDriveSlugs(host);\n if (!known) return;\n // A literal address may carry the hashed slug of a `projectHash` drive.\n const names = (slug: string, served: string) =>\n served === slug ||\n (served.startsWith(`${slug}-`) &&\n /^[0-9a-f]{8}$/.test(served.slice(slug.length + 1)));\n for (const slug of placed) {\n if (known.some((served) => names(slug, served))) continue;\n ctx.addIssue({\n code: \"custom\",\n path: [\"reactor\", \"placement\", \"drives\", slug],\n message: `placement.drives.${slug} names no drive this host links to or declares (${[...new Set(known)].join(\", \") || \"none\"}).`,\n });\n }\n}\n\ninterface ResolvedReactorBlock {\n backends?: Record<string, { kind: string; remote?: { url: unknown } }>;\n placement?: { drives?: Record<string, string> };\n drives?: unknown;\n}\n\n/** Resolved-form checks across backends, drives and placement: one base is\n * one remote backend, and a drive placed on a remote is on its switchboard. */\nfunction refineResolvedReactor(\n reactor: ResolvedReactorBlock,\n ctx: z.RefinementCtx,\n): void {\n const backends = reactor.backends ?? {};\n const baseOf = new Map<string, string>();\n const byBase = new Map<string, string>();\n // Every switchboard a slug is linked on: one slug on two is ambiguous.\n const linked = new Map<string, Set<string>>();\n const link = (slug: string, base: string) =>\n linked.set(slug, (linked.get(slug) ?? new Set()).add(base));\n for (const [name, backend] of Object.entries(backends)) {\n const url = backend.remote?.url;\n if (backend.kind !== \"remote\" || typeof url !== \"string\") continue;\n const home = switchboardOfDrive(url);\n if (!home) continue;\n baseOf.set(name, home.base);\n link(home.slug, home.base);\n const first = byBase.get(home.base);\n if (first === undefined) {\n byBase.set(home.base, name);\n continue;\n }\n ctx.addIssue({\n code: \"custom\",\n path: [\"backends\", name, \"remote\", \"url\"],\n message: `backends \"${first}\" and \"${name}\" both open drives on the same switchboard (${home.base}). Keep \"${first}\", and list the second drive under reactor.drives with its remote.url instead.`,\n });\n }\n\n const kept = new Set<string>();\n const declared = Array.isArray(reactor.drives)\n ? (reactor.drives as { slug: string; remote?: { url: string } }[])\n : [];\n declared.forEach((drive, index) => {\n if (!drive.remote) {\n kept.add(drive.slug);\n return;\n }\n const at = switchboardOfDrive(drive.remote.url);\n // An empty url already fails the field's own check.\n if (at || drive.remote.url === \"\") {\n if (at) link(drive.slug, at.base);\n return;\n }\n ctx.addIssue({\n code: \"custom\",\n path: [\"drives\", index, \"remote\", \"url\"],\n message: `remote.url must be a switchboard drive address (<switchboard>/d/<slug>), not ${drive.remote.url}: sync needs the drive. Use url: switchboard.drives.<slug>.url, or url: { $output: { host: \"switchboard\", path: [\"drives\", \"<slug>\", \"url\"] } }.`,\n });\n });\n\n const nameOf = (base: string) => byBase.get(base) ?? base;\n for (const [slug, name] of Object.entries(reactor.placement?.drives ?? {})) {\n const at = [\"placement\", \"drives\", slug];\n const on = [...(linked.get(slug) ?? [])];\n // Two drives answer to the key, whichever backend it names.\n if (on.length > 0 && kept.has(slug)) {\n ctx.addIssue({\n code: \"custom\",\n path: at,\n message: `Drive \"${slug}\" is both this reactor's own drive and on ${on.map(nameOf).join(\" and \")}. Rename one, or link only one.`,\n });\n continue;\n }\n if (on.length > 1) {\n ctx.addIssue({\n code: \"custom\",\n path: at,\n message: `Drive \"${slug}\" is on both ${on.map(nameOf).join(\" and \")}. Rename one, or link only one.`,\n });\n continue;\n }\n const base = baseOf.get(name);\n if (base === undefined) continue;\n if (on.length === 0) {\n // A key that names no drive here (a hashed home drive) is not checked.\n if (!kept.has(slug)) continue;\n ctx.addIssue({\n code: \"custom\",\n path: at,\n message: `placement.drives.${slug} opens drive \"${slug}\" on \"${name}\", but this reactor keeps that drive itself. Only a drive on a switchboard can open there without a copy.`,\n });\n continue;\n }\n if (on[0] === base) continue;\n ctx.addIssue({\n code: \"custom\",\n path: at,\n message: `placement.drives.${slug} opens drive \"${slug}\" on \"${name}\" (${base}), but the drive is on ${on[0]}. Place it on the backend for that switchboard.`,\n });\n }\n}\n\n/** `remote` keys that tune a connection, so only a remote backend has them. */\nconst REMOTE_ONLY_KEYS = [\"requestTimeoutMs\", \"breaker\", \"realtime\"] as const;\n\n/**\n * Builds the host schema set. \"allow\" (declared form) accepts `T | Token` in\n * every token-able field; \"forbid\" (resolved form) accepts `T` only.\n */\nfunction buildHostSchemas(tokenField: FieldWrappers) {\n const resolved = tokenField === FORBID_TOKENS;\n const reactorBackendSchema = z\n .strictObject({\n kind: reactorBackendKindSchema,\n storage: z\n .strictObject({\n kind: z.enum([\"idb\", \"memory\", \"path\", \"postgres\"]),\n /** `\"${userData}/…\"` sugar or `{ $env: \"NAME\" }`. */\n dataDir: tokenField.env(z.string()).optional(),\n url: z.string().optional(),\n })\n .optional(),\n readModel: z.strictObject({ url: z.string().optional() }).optional(),\n packages: z\n .strictObject({\n cdnUrl: z.string().optional(),\n specs: z.array(z.string()).optional(),\n /** on-demand model resolution (was DYNAMIC_MODEL_LOADING). */\n dynamic: z.boolean().optional(),\n })\n .optional(),\n // A switchboard drive address, `<base>/d/<slug>`: typically a\n // producer's `drives.<slug>.url` output token. The backend is the\n // switchboard at `<base>`. `${origin}/d/<slug>` when the member's own\n // server proxies the switchboard (the browser then calls its page\n // origin; see `runner.proxy` on the connect runner).\n remote: z\n .strictObject({\n url: tokenField.any(originOrUrlSchema),\n /** Give up on one request to this switchboard after this long. Default 30_000. */\n requestTimeoutMs: z.number().int().positive().optional(),\n /** After `failures` failed requests in a row, send nothing for\n * `openMs`. Default { failures: 3, openMs: 30_000 }. `false`:\n * never stop trying. */\n breaker: z\n .union([\n z.literal(false),\n z.strictObject({\n failures: z.number().int().min(1).optional(),\n openMs: z.number().int().nonnegative().optional(),\n }),\n ])\n .optional(),\n /** Live updates over a socket (the router's GraphQL\n * subscriptions, not drive sync). Default true. */\n realtime: z.boolean().optional(),\n })\n .optional(),\n })\n // Two PGlite instances on one data dir corrupt it: the reactor store\n // (storage.dataDir) and the read-model store (readModel.url) must differ.\n // Postgres is exempt: one database legitimately serves both stores.\n .superRefine((backend, ctx) => {\n // 2.1 \"a remote backend needs url\": `remote` is optional for the\n // in-process/worker kinds, but a remote backend attaches by URL only.\n if (backend.kind === \"remote\" && !backend.remote) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"remote\", \"url\"],\n message: `a \"remote\" backend needs remote.url, a switchboard drive address: ${useDriveUrl()}.`,\n });\n }\n if (backend.kind !== \"remote\" && backend.remote) {\n for (const key of REMOTE_ONLY_KEYS) {\n if (backend.remote[key] === undefined) continue;\n ctx.addIssue({\n code: \"custom\",\n path: [\"remote\", key],\n message: `remote.${key} applies only to a \"remote\" backend; this one is \"${backend.kind}\".`,\n });\n }\n }\n const url: unknown = backend.remote?.url;\n const graphqlRef = resolved ? undefined : endpointsGraphqlRef(url);\n if (graphqlRef) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"remote\", \"url\"],\n message: `remote.url reads ${graphqlRef.host}'s endpoints.graphql; it must be a switchboard drive address (<switchboard>/d/<slug>): sync needs the drive. Use ${useDriveUrl(graphqlRef.host, graphqlRef.member)}.`,\n });\n }\n if (resolved && typeof url === \"string\" && !switchboardOfDrive(url)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"remote\", \"url\"],\n message: `remote.url must be a switchboard drive address (<switchboard>/d/<slug>), not ${url}: sync needs the drive. Use ${useDriveUrl()}.`,\n });\n }\n const store = backend.storage;\n const storeDir = store?.kind === \"path\" ? store.dataDir : undefined;\n const readModel = backend.readModel?.url;\n // In the declared form dataDir may still be a `$env` token: compare\n // only resolved strings (resolved validation re-runs this check).\n if (\n typeof storeDir === \"string\" &&\n readModel &&\n samePath(storeDir, readModel)\n ) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"readModel\", \"url\"],\n message:\n `readModel.url must not be the reactor's storage dir (${readModel}): ` +\n \"two PGlite instances on one data dir corrupt it. Omit readModel.url \" +\n \"to get the classic <root>/.ph/read-storage next to the reactor store.\",\n });\n }\n });\n\n const reactorSchema = z\n .strictObject({\n backends: z.record(z.string(), reactorBackendSchema).optional(),\n placement: z\n .strictObject({\n primary: z.string().optional(),\n /** Declared drive slug → backend name. A local backend keeps a\n * synced copy; the drive's own remote backend opens it there with\n * no copy. An unlisted drive keeps a synced copy. */\n drives: z.record(z.string().min(1), z.string().min(1)).optional(),\n /** The backend new drives (and documents outside a drive) are\n * created on. A switchboard keeps no copy in this browser.\n * Default: the browser reactor, else the only switchboard. */\n newDrives: z.string().min(1).optional(),\n })\n .optional(),\n router: z\n .strictObject({\n /** Wait this long for a reactor to say whether it holds a\n * document. 0: no bound. Default 3_000. */\n probeTimeoutMs: z.number().int().nonnegative().optional(),\n /** Look again after this long for a document found on a later\n * backend. Default 30_000. */\n provisionalRouteMs: z.number().int().nonnegative().optional(),\n })\n .optional(),\n protocol: reactorProtocolSchema.optional(),\n /** DEPRECATED (dies in R2): workflows become a listed plugin. */\n workflows: z.boolean().optional(),\n // R1 core keys: identity/signing and storage namespace.\n renown: z\n .strictObject({\n url: z.string().optional(),\n networkId: z.string().optional(),\n chainId: z.number().int().optional(),\n })\n .optional(),\n namespace: z.string().min(1).optional(),\n // Core-declared, seeded by the host runtime. Token-able as a whole\n // (3.3): a `$map` over a producer's `drives` output (or an `$output` of\n // an array of declarations) renders the list at resolve time.\n drives: tokenField\n .any(z.array(buildDriveDeclarationSchema(tokenField.any)))\n .optional(),\n })\n .superRefine((reactor, ctx) => {\n const backends = reactor.backends ?? {};\n for (const [slug, name] of Object.entries(\n reactor.placement?.drives ?? {},\n )) {\n if (Object.hasOwn(backends, name)) continue;\n ctx.addIssue({\n code: \"custom\",\n path: [\"placement\", \"drives\", slug],\n message: `placement.drives.${slug} names backend \"${name}\", which is not in backends (${Object.keys(backends).join(\", \") || \"none\"}).`,\n });\n }\n const newDrives = reactor.placement?.newDrives;\n if (newDrives !== undefined && !Object.hasOwn(backends, newDrives)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"placement\", \"newDrives\"],\n message: `placement.newDrives names backend \"${newDrives}\", which is not in backends (${Object.keys(backends).join(\", \") || \"none\"}).`,\n });\n }\n if (resolved) refineResolvedReactor(reactor, ctx);\n });\n\n /** Common runner options; runner modules extend it with their own. */\n const runnerBaseSchema = z.looseObject({\n module: z.string().min(1),\n defaultVerb: z.string().min(1).optional(),\n port: z.number().int().positive().optional(),\n /** Bind address; each runner documents its default. */\n host: z.string().min(1).optional(),\n /** THE COMPOSITION: plugin entries; presence is activation. */\n plugins: z.array(pluginEntrySchema).optional(),\n });\n\n /** A compound member wrapper. Sections are FULL STATEMENTS except `runner`,\n * which key-merges over the member's own. Plugins live in `runner.plugins`\n * (as on a standalone host); there is no wrapper-level `plugins`. */\n const childWrapperSchema = z.strictObject({\n host: z.string().min(1),\n // 0 passes here; the member runner's own schema decides whether it may.\n runner: runnerBaseSchema\n .partial()\n .extend({ port: z.number().int().min(0).max(65535).optional() })\n .optional(),\n config: z.looseObject({}).optional(),\n reactor: reactorSchema.optional(),\n });\n\n const childrenSchema = z.record(z.string(), childWrapperSchema);\n\n const reactorHostSchema = z.strictObject({\n name: hostNameSchema,\n runner: runnerBaseSchema,\n config: z.looseObject({}).optional(),\n profile: profileSchema.optional(),\n reactor: reactorSchema.optional(),\n });\n\n const compoundHostSchema = z.strictObject({\n name: hostNameSchema,\n runner: runnerBaseSchema,\n children: childrenSchema,\n config: z.looseObject({}).optional(),\n profile: profileSchema.optional(),\n });\n\n return {\n reactorBackendSchema,\n reactorSchema,\n runnerBaseSchema,\n childWrapperSchema,\n childrenSchema,\n reactorHostSchema,\n compoundHostSchema,\n /** This set's field wrapper, for a runner's OWN token-able fields inside\n * `defineHostSchemas`: declared, `T | Token` in and `T` out; resolved,\n * `T` only. Both modes share one static type. */\n tokenable: tokenField.any,\n /** As `tokenable`, but the only token accepted is `$env`. */\n envTokenable: tokenField.env,\n };\n}\n\nexport type HostSchemas = ReturnType<typeof buildHostSchemas>;\n\n/** The host schema set in declared (\"allow\": token-able fields take tokens)\n * or resolved (\"forbid\") form. */\nexport function makeHostSchemas(options: { tokens: TokenMode }): HostSchemas {\n return buildHostSchemas(\n options.tokens === \"allow\" ? ALLOW_TOKENS : FORBID_TOKENS,\n );\n}\n\nexport type PlacementKeyIssue = {\n path: (string | number)[];\n message: string;\n};\n\n/** The issues a host-level refinement raises, outside a zod parse. */\nfunction collectIssues(\n host: unknown,\n refine: (host: DeclaredReactorHost, ctx: z.RefinementCtx) => void,\n): PlacementKeyIssue[] {\n if (typeof host !== \"object\" || host === null || !(\"reactor\" in host)) {\n return [];\n }\n const issues: PlacementKeyIssue[] = [];\n const ctx = {\n addIssue: (issue: { path?: PropertyKey[]; message?: string }) => {\n issues.push({\n path: (issue.path ?? []).filter(\n (part): part is string | number => typeof part !== \"symbol\",\n ),\n message: issue.message ?? \"\",\n });\n },\n } as unknown as z.RefinementCtx;\n refine(host as DeclaredReactorHost, ctx);\n return issues;\n}\n\n/** withPlacementKeys' check, for a merged declared host parsed some other way. */\nexport function placementKeyIssues(host: unknown): PlacementKeyIssue[] {\n return collectIssues(host, refineDeclaredPlacementKeys);\n}\n\nexport const CONNECT_PRIMARY_MESSAGE =\n \"Connect doesn't use placement.primary. To choose where new drives go, use placement.newDrives.\";\n\n/**\n * A Connect host's placement rules, in either form. The router's primary is\n * the browser reactor, else the `newDrives` switchboard, else the only one,\n * so `placement.primary` means nothing here, and a Connect with several\n * switchboards and no browser reactor must say where new drives go. Apply it\n * last to the Connect runner's schema: `.superRefine(refineConnectReactor)`.\n */\nexport function refineConnectReactor(\n host: { reactor?: unknown },\n ctx: z.RefinementCtx,\n): void {\n const reactor = (host as DeclaredReactorHost).reactor;\n if (!reactor) return;\n if (reactor.placement?.primary !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"reactor\", \"placement\", \"primary\"],\n message: CONNECT_PRIMARY_MESSAGE,\n });\n }\n const backends = Object.entries(reactor.backends ?? {});\n const remotes = backends\n .filter(([, backend]) => backend.kind === \"remote\")\n .map(([name]) => name);\n if (\n remotes.length > 1 &&\n remotes.length === backends.length &&\n reactor.placement?.newDrives === undefined\n ) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"reactor\", \"placement\", \"newDrives\"],\n message: `This Connect keeps no reactor in the browser and links ${remotes.length} switchboards (${remotes.join(\", \")}). Set placement.newDrives to the one new drives are created on.`,\n });\n }\n}\n\n/** refineConnectReactor's check, for a Connect host parsed some other way. */\nexport function connectReactorIssues(host: unknown): PlacementKeyIssue[] {\n return collectIssues(host, refineConnectReactor);\n}\n\n/** Adds the host-level placement key check to a runner's declared schema. */\nfunction withPlacementKeys<T>(schema: T): T {\n if (!(schema instanceof z.ZodType)) return schema;\n return schema.superRefine((host, ctx) => {\n if (typeof host === \"object\" && host !== null && \"reactor\" in host) {\n refineDeclaredPlacementKeys(host as DeclaredReactorHost, ctx);\n }\n }) as T;\n}\n\n/**\n * One runner definition, two schemas (3.5): `build` runs over the DECLARED\n * set (tokens allowed; its z.input types host files) and the RESOLVED set\n * (no tokens; `validateHost` checks it before the verb). Export both, type\n * the host as `z.input<typeof declaredHostSchema>`, refine last inside the\n * builder (zod can't extend a refined object), and wrap the runner's own\n * token-able fields with `s.tokenable` / `s.envTokenable`.\n */\nexport function defineHostSchemas<T>(build: (schemas: HostSchemas) => T): {\n declaredHostSchema: T;\n hostSchema: T;\n} {\n return {\n declaredHostSchema: withPlacementKeys(build(declaredSchemas)),\n hostSchema: build(resolvedSchemas),\n };\n}\n\nconst declaredSchemas = makeHostSchemas({ tokens: \"allow\" });\nconst resolvedSchemas = makeHostSchemas({ tokens: \"forbid\" });\n\n/* The exported base blocks are the RESOLVED form (what verbs receive). The\n * declared forms are `declaredHostSchemas` / `defineHostSchemas`. */\nexport const declaredHostSchemas: HostSchemas = declaredSchemas;\nexport const reactorBackendSchema = resolvedSchemas.reactorBackendSchema;\nexport const reactorSchema = resolvedSchemas.reactorSchema;\nexport const runnerBaseSchema = resolvedSchemas.runnerBaseSchema;\nexport const childWrapperSchema = resolvedSchemas.childWrapperSchema;\nexport const childrenSchema = resolvedSchemas.childrenSchema;\nexport const reactorHostSchema = resolvedSchemas.reactorHostSchema;\nexport const compoundHostSchema = resolvedSchemas.compoundHostSchema;\n\n/** The generic compound runner's host: the base with its wiring config. */\nconst genericCompound = defineHostSchemas((s) =>\n s.compoundHostSchema\n .extend({ config: compoundWiringSchema.optional() })\n .superRefine(refineStartOrder),\n);\nexport const genericCompoundHostSchema = genericCompound.hostSchema;\nexport const declaredGenericCompoundHostSchema =\n genericCompound.declaredHostSchema;\n\n/* -------------------------------------------------------------------- types */\n\nexport type Profile = z.infer<typeof profileSchema>;\nexport type ReactorProtocol = z.infer<typeof reactorProtocolSchema>;\nexport type ReactorBackend = z.infer<typeof reactorBackendSchema>;\nexport type ReactorBackendKind = ReactorBackend[\"kind\"];\nexport type ReactorStorageConfig = NonNullable<ReactorBackend[\"storage\"]>;\nexport type ReactorPackageConfig = NonNullable<ReactorBackend[\"packages\"]>;\nexport type ReactorRemoteConfig = NonNullable<ReactorBackend[\"remote\"]>;\nexport type ReactorConfig = z.infer<typeof reactorSchema>;\nexport type RunnerBase = z.infer<typeof runnerBaseSchema>;\nexport type ChildWrapper = z.infer<typeof childWrapperSchema>;\nexport type CompoundWiring = z.infer<typeof compoundWiringSchema>;\n\n/** What a host.js author writes (z.input), per runner kind. The `never`\n * sides make reactor XOR children a type error. */\nexport type ReactorHostInput = z.input<\n typeof declaredSchemas.reactorHostSchema\n> & {\n children?: never;\n};\nexport type CompoundHostInput = z.input<\n typeof declaredSchemas.compoundHostSchema\n> & {\n reactor?: never;\n};\nexport type HostDefinition = ReactorHostInput | CompoundHostInput;\n\n/** What a verb receives (z.output) from the base schemas. */\nexport type ReactorHost = z.output<typeof reactorHostSchema>;\nexport type CompoundHost = z.output<typeof compoundHostSchema>;\n\n/* --------------------------------------------------------------- JSON Schema */\n\nconst SCHEMA_BASE = \"https://powerhouse.inc/schemas\";\n\n/** One host schema as an editor JSON Schema with a stable `$id` — the\n * per-runner emission helper (runner packages emit their own hostSchema). */\nexport function emitHostJsonSchema(\n name: string,\n schema: z.ZodType,\n): Record<string, unknown> {\n return {\n $id: `${SCHEMA_BASE}/${name}.schema.json`,\n ...z.toJSONSchema(schema, { io: \"input\" }),\n };\n}\n\n/** The emitted-schema set, keyed by published filename. Pure — the\n * emit-schemas script writes these and the drift test re-derives them. */\nexport function emittedHostSchemas(): Record<string, unknown> {\n return {\n // Editor schemas describe what authors write: the declared form.\n \"host-reactor.schema.json\": emitHostJsonSchema(\n \"host-reactor\",\n declaredSchemas.reactorHostSchema,\n ),\n \"host-compound.schema.json\": emitHostJsonSchema(\n \"host-compound\",\n declaredSchemas.compoundHostSchema,\n ),\n };\n}\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 { 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","/**\n * Pure built-in `$env` substitution: the `\"${userData}\"` / `\"${projectRoot}\"`\n * string sugar, deep-applied to a JSON-shaped value. No node imports, so it\n * ships in `./schema`; the node default for userData is placeholders.ts.\n */\n\nexport interface BuiltinEnv {\n userData?: string;\n projectRoot?: string;\n}\n\n/** The always-resolvable `$env` names (also the `\"${name}\"` sugar). */\nexport const BUILTIN_ENV_NAMES: readonly (keyof BuiltinEnv)[] = [\n \"userData\",\n \"projectRoot\",\n];\n\nexport function isBuiltinEnvName(name: string): name is keyof BuiltinEnv {\n return (BUILTIN_ENV_NAMES as readonly string[]).includes(name);\n}\n\nconst BUILTIN = new RegExp(`\\\\$\\\\{(${BUILTIN_ENV_NAMES.join(\"|\")})\\\\}`, \"g\");\n\nfunction substitute(text: string, env: BuiltinEnv): string {\n return text.replace(\n BUILTIN,\n (match, name: keyof BuiltinEnv) => env[name] ?? match,\n );\n}\n\n/** Deep-substitute the built-ins that `env` provides in every string; an\n * absent built-in is left as written. The input is never mutated. */\nexport function substituteBuiltinEnv<T>(value: T, env: BuiltinEnv): T {\n return substituteValue(value, env) as T;\n}\n\nfunction substituteValue(value: unknown, env: BuiltinEnv): unknown {\n if (typeof value === \"string\") return substitute(value, env);\n if (Array.isArray(value)) return value.map((v) => substituteValue(v, env));\n if (value !== null && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n out[k] = substituteValue(v, env);\n }\n return out;\n }\n return value;\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\n/**\n * What a one-shot verb (build) gets for a `$map`: no outputs exist there, so\n * every map in `declared` renders no elements (`[]`, or `{}` with into:\n * \"record\") at its path in `host`, the declared-form parse of `declared`.\n * Other tokens stay, as they do in token-able fields.\n */\nexport function emptyMaps<T>(host: T, declared: unknown): T {\n const maps = collectTokenSites(declared).filter(\n (site) =>\n site.key === \"$map\" &&\n site.scopes.length === 0 &&\n site.position !== \"concat\",\n );\n if (maps.length === 0) return host;\n const out: unknown = cloneWithProvenance(host);\n for (const { path, token } of maps) {\n const operand = token.$map;\n const record = isPlainObject(operand) && operand.into === \"record\";\n setAt(out, path, record ? {} : [], false);\n }\n return out as T;\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 { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { runnerKindSchema, type RunnerKind } from \"./host-schemas.js\";\nimport {\n checkOutputPaths,\n checkTokenSites,\n type DeclaredIssue,\n type OutputRef,\n type OutputsSchemaLookup,\n} from \"./resolve/declared.js\";\nimport { findRemovedForms } from \"./resolve/removed-forms.js\";\nimport { describeMapElements } from \"./resolve/resolve.js\";\nimport { formatPath, unwrapEscapes } from \"./resolve/walk.js\";\nimport { findToken, tokenKeyOf, type TokenMode } from \"./tokens.js\";\n\n/**\n * Resolves a host's `runner.module` specifier from the PROJECT's dependency\n * tree (not ph-cli's), imports it, and checks the runner-module contract:\n * `{ run, hostSchema, kind, outputsSchema?, verbs?, ...optionalVerbs }`.\n */\n\nexport class RunnerError extends Error {\n constructor(message: string, hint?: string) {\n super(hint ? `${message}\\n Hint: ${hint}` : message);\n this.name = \"RunnerError\";\n }\n}\n\nexport interface RunnerContext {\n projectRoot: string;\n /** The verb this runner runs at. For a compound member it is the member's\n * OWN effective verb (e.g. \"serve\" under a compound at \"run\"). */\n verb: string;\n env: Record<string, string | undefined>;\n /** Set when this runner runs as a compound member: the compound's host\n * name and verb. */\n parent?: { host: string; verb: string };\n /** This invocation's arguments for this runner: what followed\n * `ph run <host> [verb]`, checked against the runner's `argsSchema`. They\n * win over the host file. A compound member gets its own share. */\n argv?: readonly string[];\n}\n\n/** A verb receives the PARSED host (its runner's hostSchema output), so\n * schema defaults and transforms reach it. */\nexport type RunnerVerb<O = unknown> = (\n host: O,\n ctx: RunnerContext,\n) => Promise<unknown>;\n\nexport interface HostSchemaIssue {\n path: PropertyKey[];\n message: string;\n code?: string;\n}\n\n/** zod-shaped structurally, so a runner may bring its own zod instance. */\nexport interface HostSchemaLike<O = unknown> {\n safeParse(\n host: unknown,\n ):\n | { success: true; data: O }\n | { success: false; error: { issues: readonly HostSchemaIssue[] } };\n}\n\n/** Whether a value is zod-shaped (has a `safeParse` function): a runner's\n * `outputsSchema`, a plugin's config schema. */\nexport function isSchemaLike(value: unknown): value is HostSchemaLike {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"safeParse\" in value &&\n typeof value.safeParse === \"function\"\n );\n}\n\n/** The Connect runner's specifier: compounds forward `cspRegistrySync` to\n * it, and `--explain` prints its dead-config warnings. */\nexport const CONNECT_RUNNER = \"@powerhousedao/ph-cli/runners/connect\";\n\nexport interface RunnerModule<O = unknown> {\n run: RunnerVerb<O>;\n /** The RESOLVED host schema: no tokens; checked right before the verb. */\n hostSchema: HostSchemaLike<O>;\n /** The DECLARED host schema (token-able fields accept tokens), from the\n * same definition (`defineHostSchemas`). Absent: declared validation\n * checks the tokens only, and shape errors surface at resolved\n * validation. */\n declaredHostSchema?: HostSchemaLike;\n kind: RunnerKind;\n /** What a started host produces (G3); `$output` paths are checked\n * against it. Absent: the runner produces no outputs. */\n outputsSchema?: unknown;\n /** The verb names, when the module exports functions that are not verbs\n * (helpers). Absent: every exported function is a verb. */\n verbs?: readonly string[];\n /** The arguments the runner accepts after `ph run <host> [verb]`\n * (`RunnerArgsSchema`). Absent: it accepts none, and any argument fails. */\n argsSchema?: unknown;\n /** What the verb would refuse at boot, given the parsed host and an\n * environment (`ph host check`). Starts nothing. */\n checkBoot?: (\n host: O,\n ctx: BootCheckContext,\n ) => readonly BootIssue[] | Promise<readonly BootIssue[]>;\n [key: string]: unknown;\n}\n\nexport interface BootCheckContext {\n projectRoot: string;\n /** The verb the host would run at (a compound member's own verb). */\n verb: string;\n /** The environment the verb would see; never `process.env` implicitly. */\n env: Readonly<Record<string, string | undefined>>;\n /** The host file, for messages (`hosts/switchboard/host.js`). */\n file: string;\n}\n\nexport interface BootIssue {\n path?: string;\n message: string;\n hint?: string;\n}\n\n/** Exports that are part of the contract but are not verbs. */\nconst NON_VERB_EXPORTS = new Set([\n \"hostSchema\",\n \"declaredHostSchema\",\n \"outputsSchema\",\n \"verbs\",\n \"argsSchema\",\n \"kind\",\n \"checkBoot\",\n \"default\",\n]);\n\n/** ph-cli's runners are ph-run's plus the verbs that build. A packaged app has\n * only ph-run, and its host files, generated against ph-cli's, name ph-cli's. */\nexport function runnerFallback(specifier: string): string | undefined {\n const name = /^@powerhousedao\\/ph-cli\\/(runners\\/.+)$/.exec(specifier)?.[1];\n return name ? `@powerhousedao/ph-run/${name}` : undefined;\n}\n\nexport async function resolveRunnerModule(\n projectRoot: string,\n specifier: string,\n): Promise<RunnerModule> {\n const projectRequire = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n const resolveFirst = (candidates: string[]): string => {\n const [first, ...rest] = candidates;\n try {\n return projectRequire.resolve(first);\n } catch (error) {\n if (rest.length === 0) throw error;\n return resolveFirst(rest);\n }\n };\n let resolved: string;\n try {\n const fallback = runnerFallback(specifier);\n resolved = resolveFirst(fallback ? [specifier, fallback] : [specifier]);\n } catch {\n throw new RunnerError(\n `Cannot resolve runner module \"${specifier}\" from ${projectRoot}.`,\n \"The runner must be a dependency of the project (install it, then retry).\",\n );\n }\n\n const module = (await import(pathToFileURL(resolved).href)) as Record<\n string,\n unknown\n >;\n\n if (typeof module.run !== \"function\") {\n throw new RunnerError(\n `Runner \"${specifier}\" does not export a \\`run\\` function (required verb).`,\n );\n }\n const hostSchema = module.hostSchema as HostSchemaLike | undefined;\n if (!hostSchema || typeof hostSchema.safeParse !== \"function\") {\n throw new RunnerError(\n `Runner \"${specifier}\" does not export a \\`hostSchema\\` — runners validate their own host shape.`,\n );\n }\n const declared = module.declaredHostSchema as HostSchemaLike | undefined;\n if (declared !== undefined && typeof declared.safeParse !== \"function\") {\n throw new RunnerError(\n `Runner \"${specifier}\" exports a \\`declaredHostSchema\\` without safeParse.`,\n );\n }\n if (\n module.checkBoot !== undefined &&\n typeof module.checkBoot !== \"function\"\n ) {\n throw new RunnerError(\n `Runner \"${specifier}\" exports a \\`checkBoot\\` that is not a function.`,\n );\n }\n const verbs = module.verbs;\n if (\n verbs !== undefined &&\n (!Array.isArray(verbs) ||\n !verbs.every(\n (verb: unknown) =>\n typeof verb === \"string\" && typeof module[verb] === \"function\",\n ))\n ) {\n throw new RunnerError(\n `Runner \"${specifier}\" exports \\`verbs\\` ${JSON.stringify(verbs)}, which must list names of exported functions.`,\n );\n }\n if (!runnerKindSchema.safeParse(module.kind).success) {\n throw new RunnerError(\n `Runner \"${specifier}\" does not export a valid \\`kind\\` (got ${JSON.stringify(module.kind)}; expected \"reactor\" | \"compound\").`,\n );\n }\n return module as unknown as RunnerModule;\n}\n\n/** Verbs that produce something and start nothing (`build`): no outputs, no\n * record, no lock — and no token resolution, since what they read (output\n * dirs, packages) never comes from another host's outputs. Their verb gets\n * the declared host (tokens may remain in token-able fields; a `$map` is\n * the empty collection, see `emptyMaps`). */\nexport const ONE_SHOT_VERBS: ReadonlySet<string> = new Set([\"build\"]);\n\n/** Verbs that work on a host's stores and start nothing (`migrate`,\n * `migrate-status`, `reset`). Their host is resolved as for `run`, so they\n * address the stores `run` opens; they take no lock and return nothing, so\n * no record is written. A compound does not forward them. */\nexport const STORE_VERBS: ReadonlySet<string> = new Set([\n \"migrate\",\n \"migrate-status\",\n \"reset\",\n]);\n\nexport function listVerbs<O>(runner: RunnerModule<O>): string[] {\n if (runner.verbs) {\n return runner.verbs\n .filter((name) => typeof runner[name] === \"function\")\n .toSorted();\n }\n return Object.entries(runner)\n .filter(\n ([name, value]) =>\n typeof value === \"function\" && !NON_VERB_EXPORTS.has(name),\n )\n .map(([name]) => name)\n .sort();\n}\n\nexport function getVerb<O>(\n runner: RunnerModule<O>,\n specifier: string,\n verb: string,\n): RunnerVerb<O> {\n const candidate = runner[verb];\n if (typeof candidate !== \"function\" || !listVerbs(runner).includes(verb)) {\n throw new RunnerError(\n `Runner \"${specifier}\" does not support the verb \"${verb}\". Supported verbs: ${listVerbs(\n runner,\n ).join(\", \")}.`,\n );\n }\n return candidate as RunnerVerb<O>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** A contract violation found while validating a host, without the file\n * prefix the throwing validators add. */\nexport interface RunnerIssue {\n path: string;\n message: string;\n hint?: string;\n}\n\n/** reactor XOR children, decided by the runner's declared `kind`. */\nexport function kindShapeIssues(\n kind: RunnerKind,\n specifier: string,\n host: Record<string, unknown>,\n): RunnerIssue[] {\n if (kind === \"reactor\" && host.children !== undefined) {\n return [\n {\n path: \"children\",\n message: `\"${specifier}\" is a reactor runner, so the host must not declare \\`children\\`.`,\n hint: \"`children` belongs to compound hosts; a reactor host configures its own `reactor` block.\",\n },\n ];\n }\n if (kind === \"compound\" && host.reactor !== undefined) {\n return [\n {\n path: \"reactor\",\n message: `\"${specifier}\" is a compound runner, so the host must not declare \\`reactor\\`.`,\n hint: \"A compound's reactors are its members': configure them in the member host or a wrapper's `reactor` override.\",\n },\n ];\n }\n return [];\n}\n\nfunction assertKindShape(\n kind: RunnerKind,\n specifier: string,\n host: Record<string, unknown>,\n file: string,\n): void {\n const issue = kindShapeIssues(kind, specifier, host).at(0);\n if (issue) throw new RunnerError(`${file}: ${issue.message}`, issue.hint);\n}\n\n/** `runner.defaultVerb` and every plugin entry's `verbs` must name verbs\n * this runner exports. */\nexport function knownVerbIssues<O>(\n runner: RunnerModule<O>,\n specifier: string,\n host: Record<string, unknown>,\n): RunnerIssue[] {\n const options = host.runner;\n if (!isRecord(options)) return [];\n const verbs = listVerbs(runner);\n const unknownVerb = (verb: unknown): verb is string =>\n typeof verb === \"string\" && !verbs.includes(verb);\n const issues: RunnerIssue[] = [];\n if (unknownVerb(options.defaultVerb)) {\n issues.push({\n path: \"runner.defaultVerb\",\n message: `runner.defaultVerb \"${options.defaultVerb}\" is not a verb of \"${specifier}\". Supported verbs: ${verbs.join(\", \")}.`,\n });\n }\n const plugins: unknown[] = Array.isArray(options.plugins)\n ? options.plugins\n : [];\n plugins.forEach((entry, index) => {\n if (!isRecord(entry) || !Array.isArray(entry.verbs)) return;\n const scoped: unknown[] = entry.verbs;\n for (const bad of scoped.filter(unknownVerb)) {\n issues.push({\n path: `runner.plugins[${index}].verbs`,\n message: `plugin \"${String(entry.module)}\" is scoped to verb \"${bad}\", which \"${specifier}\" does not export. Supported verbs: ${verbs.join(\", \")}.`,\n });\n }\n });\n return issues;\n}\n\nfunction formatIssues(issues: readonly DeclaredIssue[]): string {\n return issues.map((i) => ` - ${i.path}: ${i.message}`).join(\"\\n\");\n}\n\nfunction valueAt(host: unknown, path: readonly PropertyKey[]): unknown {\n let current = host;\n for (const key of path) {\n if (Array.isArray(current) && typeof key === \"number\") {\n current = current[key];\n } else if (isRecord(current) && typeof key === \"string\") {\n current = current[key];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\nexport interface ValidateHostOptions {\n /** \"forbid\" (default): the resolved form, checked with `hostSchema`; no\n * token may remain. \"allow\": the declared form, checked with\n * `declaredHostSchema` (else `hostSchema`) — what a COMPOUND runner's verb\n * receives, since its members resolve their own tokens. */\n tokens?: TokenMode;\n}\n\n/**\n * Resolved validation (pipeline step 6): validate a RESOLVED host against\n * its runner's `hostSchema` and return the PARSED host (what the verb\n * receives). Run `resolveHostOutputs` first; a token still present fails\n * with its path.\n */\nexport function validateHost<O>(\n runner: RunnerModule<O>,\n specifier: string,\n host: unknown,\n file: string,\n options: ValidateHostOptions = {},\n): O {\n const schema =\n options.tokens === \"allow\"\n ? (runner.declaredHostSchema ?? runner.hostSchema)\n : runner.hostSchema;\n // Same definition (defineHostSchemas), so the declared parse has the\n // verb's shape; only token-able fields may still hold tokens.\n return parseHost(\n runner,\n schema as HostSchemaLike<O>,\n specifier,\n host,\n file,\n options,\n );\n}\n\nexport interface SchemaIssue extends RunnerIssue {\n /** The line `validateHost` prints: zod's dotted path (other runners' tests\n * match on it), then the message. */\n printed: string;\n}\n\nexport interface HostSchemaIssues<O> {\n /** Kind shape, an unresolved token (forbid mode) and unknown verbs, in\n * the order the throwing validator checks them. */\n issues: RunnerIssue[];\n /** The schema's own issues; absent when the host parsed. */\n schemaIssues?: SchemaIssue[];\n data?: O;\n}\n\n/** What `validateHost` checks, as data: nothing throws. */\nexport function hostSchemaIssues<O>(\n runner: RunnerModule<O>,\n schema: HostSchemaLike<O>,\n specifier: string,\n host: unknown,\n options: ValidateHostOptions = {},\n): HostSchemaIssues<O> {\n const issues: RunnerIssue[] = [];\n if (isRecord(host)) {\n issues.push(...kindShapeIssues(runner.kind, specifier, host));\n if (options.tokens !== \"allow\") {\n const token = findToken(host);\n if (token) {\n issues.push({\n path: token.path,\n message: `\\`${token.path}\\` is an unresolved output token (${token.key}).`,\n hint: \"Resolve the host (resolveHostOutputs) before validating it for a verb; `ph run` does this.\",\n });\n }\n }\n issues.push(...knownVerbIssues(runner, specifier, host));\n }\n // `$$` escapes protect literal `$`-keyed objects through the token walk;\n // the schema (and the verb) see the literal.\n const result = schema.safeParse(unwrapEscapes(host));\n if (result.success) return { issues, data: result.data };\n const schemaIssues = result.error.issues.map((issue): SchemaIssue => {\n const element = describeMapElements(host, issue.path);\n const dotted =\n (issue.path.map(String).join(\".\") || \"<root>\") +\n (element ? ` (${element})` : \"\");\n // A token in a field that does not take one: say so, rather than\n // the field type's own \"expected string\". A refinement's own message\n // about a token stands.\n const message =\n issue.code !== \"custom\" && tokenKeyOf(valueAt(host, issue.path))\n ? \"this field does not take an output token (it is not token-able); spell the value literally.\"\n : issue.message;\n return {\n path: formatPath(\n issue.path.filter(\n (key): key is string | number =>\n typeof key === \"string\" || typeof key === \"number\",\n ),\n ),\n message: element ? `${message} (${element})` : message,\n printed: `${dotted}: ${message}`,\n };\n });\n return { issues, schemaIssues };\n}\n\nfunction parseHost<O>(\n runner: RunnerModule<O>,\n schema: HostSchemaLike<O>,\n specifier: string,\n host: unknown,\n file: string,\n options: ValidateHostOptions,\n): O {\n const checked = hostSchemaIssues(runner, schema, specifier, host, options);\n const first = checked.issues.at(0);\n if (first) throw new RunnerError(`${file}: ${first.message}`, first.hint);\n if (checked.schemaIssues) {\n const issues = checked.schemaIssues\n .map((issue) => ` - ${issue.printed}`)\n .join(\"\\n\");\n throw new RunnerError(\n `${file} failed validation against the hostSchema of \"${specifier}\":\\n${issues || \" (no details reported)\"}`,\n );\n }\n return checked.data as O;\n}\n\nexport interface DeclaredHostOptions {\n /** Producer lookup for `$output` path checks. Absent: paths are not\n * checked here (a compound checks its members' tokens per member). */\n outputsSchemaOf?: (ref: OutputRef) => OutputsSchemaLookup;\n}\n\n/**\n * Declared validation (pipeline step 3): the removed cross-host forms\n * (each error names its token form), token shapes and `$env` `optional`\n * placement, `$output` paths against the producers' `outputsSchema`s, then\n * the runner's `declaredHostSchema` (tokens allowed in token-able fields).\n * Reads no environment value and needs no producer running. Throws on the\n * first failing stage; resolve, then `validateHost`, before a verb runs.\n */\nexport function validateDeclaredHost(\n runner: RunnerModule,\n specifier: string,\n host: unknown,\n file: string,\n options: DeclaredHostOptions = {},\n): void {\n const removed = findRemovedForms(host);\n if (removed.length > 0) {\n throw new RunnerError(`${file}: removed form:\\n${formatIssues(removed)}`);\n }\n const issues = checkTokenSites(host);\n if (options.outputsSchemaOf) {\n issues.push(...checkOutputPaths(host, options.outputsSchemaOf));\n }\n if (issues.length > 0) {\n throw new RunnerError(\n `${file}: invalid output token:\\n${formatIssues(issues)}`,\n );\n }\n if (isRecord(host)) assertKindShape(runner.kind, specifier, host, file);\n if (!runner.declaredHostSchema) return;\n parseHost(runner, runner.declaredHostSchema, specifier, host, file, {\n tokens: \"allow\",\n });\n}\n","import { createHash } from \"node:crypto\";\nimport { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { z } from \"zod\";\nimport type { HostDefinition } from \"./host-schemas.js\";\nimport type { PluginEntryData } from \"./plugins.js\";\nimport { resolvePluginContributions } from \"./plugins-resolve.js\";\nimport { resolveRunnerModule } from \"./runner-resolver.js\";\n\n/**\n * Loads and pre-validates a `hosts/<name>/host.js` definition.\n *\n * A host file is a static PROJECTION of powerhouse.config.json: plain ESM,\n * default-exporting a data object. Three gates run before any runner sees it:\n * 1. import lint — the only legal imports are the project's\n * powerhouse.config.json, sibling `../<host>/host.js` files and sibling\n * generated `../<host>/outputs.js` token trees (host files are data, not\n * programs; `process.` is banned, environment values go through `$env`).\n * An imported outputs.js whose schema hash no longer matches its\n * producer fails here (\"run `ph generate hosts`\");\n * 2. static check — the exported object must survive a JSON round trip\n * (functions, undefined, class instances, Dates etc. are rejected,\n * reporting the offending path);\n * 3. shape pre-check — `name`, `runner.module`, and the reactor XOR children\n * rule. Full validation is the runner's `hostSchema` (phase 2).\n *\n * This module never exits the process — callers own error presentation.\n */\n\nconst HOST_FILE = \"host.js\";\nconst CONFIG_IMPORT_SUFFIX = \"powerhouse.config.json\";\n\nexport class HostLoadError extends Error {\n constructor(message: string, hint?: string) {\n super(hint ? `${message}\\n Hint: ${hint}` : message);\n this.name = \"HostLoadError\";\n }\n}\n\nexport type HostsFolderStatus =\n | { kind: \"absent\" }\n | { kind: \"empty\"; dir: string }\n | { kind: \"present\"; dir: string; hosts: string[] };\n\n/** A `hosts/` folder with no `<name>/host.js` inside is \"empty\" — the guard\n * state: callers warn loudly and fall back to legacy rather than activating\n * the new architecture off a stray `mkdir hosts`. */\nexport function probeHostsFolder(projectRoot: string): HostsFolderStatus {\n const dir = path.join(projectRoot, \"hosts\");\n if (!existsSync(dir) || !statSync(dir).isDirectory()) {\n return { kind: \"absent\" };\n }\n const hosts = readdirSync(dir, { withFileTypes: true })\n .filter(\n (entry) =>\n entry.isDirectory() &&\n existsSync(path.join(dir, entry.name, HOST_FILE)),\n )\n .map((entry) => entry.name)\n .sort();\n return hosts.length === 0\n ? { kind: \"empty\", dir }\n : { kind: \"present\", dir, hosts };\n}\n\n/** Sibling imports: `../<host>/host.js` — source material for derived\n * compositions (full-inclusion wrappers compute over them with plain JS) —\n * and `../<host>/outputs.js`, the generated `$output` token tree. */\nconst SIBLING_IMPORT = /^\\.\\.\\/([A-Za-z0-9_-]+)\\/(host\\.js|outputs\\.js)$/;\n\n/** The generated per-host token tree (`ph generate hosts`). */\nexport const OUTPUTS_FILE = \"outputs.js\";\nconst GENERATE_HINT =\n \"Run `ph generate hosts` to (re)generate hosts/<name>/outputs.js from the producer's runner outputsSchema and declared drives.\";\n\n/**\n * One pass over JS source that blanks every comment and, with\n * `literals: \"blank\"`, the CONTENTS of string literals and template-literal\n * text (quotes, backticks and `${`/`}` kept). A template's `${…}` holes are\n * code: they are scanned like the rest (strings, nested templates and braces\n * inside them included). Every newline survives, so line-anchored checks and\n * line numbers still match the original source. Regex literals are not\n * recognised (host files are data; a regex is not one).\n */\nfunction scanSource(source: string, literals: \"keep\" | \"blank\"): string {\n const blank = (text: string) => text.replace(/[^\\n]/g, \" \");\n const literal = (text: string) => (literals === \"blank\" ? blank(text) : text);\n let out = \"\";\n let i = 0;\n // One entry per open `${` hole: the depth of `{` opened inside it.\n const holes: number[] = [];\n /** Template text from `i` (just after a backtick or a hole's `}`) up to\n * and including its closing backtick, or up to and including the next\n * `${` (pushing a hole). */\n const templateText = (): void => {\n let j = i;\n while (j < source.length) {\n const ch = source[j];\n if (ch === \"\\\\\") {\n j += 2;\n continue;\n }\n if (ch === \"`\") break;\n if (ch === \"$\" && source[j + 1] === \"{\") break;\n j++;\n }\n out += literal(source.slice(i, Math.min(j, source.length)));\n if (j >= source.length) {\n i = source.length;\n } else if (source[j] === \"`\") {\n out += \"`\";\n i = j + 1;\n } else {\n out += \"${\";\n holes.push(0);\n i = j + 2;\n }\n };\n while (i < source.length) {\n const ch = source[i];\n const next = source[i + 1];\n if (ch === \"/\" && next === \"/\") {\n const end = source.indexOf(\"\\n\", i);\n const stop = end === -1 ? source.length : end;\n out += blank(source.slice(i, stop));\n i = stop;\n continue;\n }\n if (ch === \"/\" && next === \"*\") {\n const end = source.indexOf(\"*/\", i + 2);\n const stop = end === -1 ? source.length : end + 2;\n out += blank(source.slice(i, stop));\n i = stop;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n // Up to the closing quote; an unterminated one stops at the newline.\n let j = i + 1;\n while (j < source.length && source[j] !== ch && source[j] !== \"\\n\") {\n j += source[j] === \"\\\\\" ? 2 : 1;\n }\n const close = source[j] === ch ? ch : \"\";\n out += ch + literal(source.slice(i + 1, Math.min(j, source.length)));\n out += close;\n i = close ? j + 1 : j;\n continue;\n }\n if (ch === \"`\") {\n out += \"`\";\n i++;\n templateText();\n continue;\n }\n if (holes.length > 0 && ch === \"{\") holes[holes.length - 1]++;\n if (holes.length > 0 && ch === \"}\") {\n if (holes[holes.length - 1] === 0) {\n holes.pop();\n out += \"}\";\n i++;\n templateText();\n continue;\n }\n holes[holes.length - 1]--;\n }\n out += ch;\n i++;\n }\n return out;\n}\n\n/** Blank out `//` and block comments, keeping string and template literals\n * (URLs contain `//`) and every newline, so line-anchored checks still see\n * the code's own lines. A JSDoc `import(\"…\")` type is a comment, not code. */\nexport function stripComments(source: string): string {\n return scanSource(source, \"keep\");\n}\n\n/** Blank out comments and the contents of string literals and\n * template-literal text, so a word inside a string (a URL, a description,\n * an apostrophe in template text) is neither mistaken for code nor able to\n * hide code. Template `${…}` holes are code and are kept. */\nfunction blankLiterals(source: string): string {\n return scanSource(source, \"blank\");\n}\n\n// Not after `.`/identifier chars: `base.runner.process.args` is a property.\nconst PROCESS_ACCESS = /(?<![.\\w$])process\\s*(?:\\?\\.|\\.|\\[)/;\n\n/** Host files and generated outputs.js are data: reading the environment\n * through `process.` is banned (typed-host-configs decision 9). Environment\n * values go through `$env`, which resolves at start in the resolving\n * process. Comments are already stripped, so a mention there is fine. */\nfunction rejectProcessAccess(source: string, file: string): void {\n const match = PROCESS_ACCESS.exec(blankLiterals(source));\n if (!match) return;\n const line = source.slice(0, match.index).split(\"\\n\").length;\n throw new HostLoadError(\n `${file}:${line} reads \\`process.\\` — host files cannot read the environment directly.`,\n 'Use an $env token instead: { $env: \"NAME\" } (fails when unset), or { $env: { name: \"NAME\", optional: true } } as a property value to omit the property when unset. It resolves when the host starts.',\n );\n}\n\n/** The imports a host file makes, after linting it. */\nexport interface HostImports {\n /** Sibling hosts whose `host.js` the file imports. */\n hosts: string[];\n /** Sibling hosts whose generated `outputs.js` the file imports. */\n outputs: string[];\n}\n\n/** Lints a host file and returns what it imports. Rejects every import\n * except the project's powerhouse.config.json, SIBLING host files (R1:\n * derived compositions) and sibling generated outputs.js token trees; any\n * dynamic `import(...)` or `require(...)`; and any `process.` access.\n * Source-level enforcement: the JSON round trip below is the hard gate; this\n * one produces the better error. */\nexport function scanHostImports(rawSource: string, file: string): HostImports {\n const source = stripComments(rawSource);\n const imports: HostImports = { hosts: [], outputs: [] };\n for (const match of source.matchAll(\n /^\\s*import\\b[^;'\"]*?from\\s+[\"']([^\"']+)[\"']/gm,\n )) {\n const specifier = match[1];\n if (specifier.endsWith(CONFIG_IMPORT_SUFFIX)) continue;\n const sibling = SIBLING_IMPORT.exec(specifier);\n if (sibling) {\n (sibling[2] === HOST_FILE ? imports.hosts : imports.outputs).push(\n sibling[1],\n );\n continue;\n }\n throw new HostLoadError(\n `${file} imports \"${specifier}\" — a host file may only import the project's powerhouse.config.json, sibling hosts/<name>/host.js files or generated hosts/<name>/${OUTPUTS_FILE} token trees.`,\n \"Host files are static projections; code belongs in plugins or the runner.\",\n );\n }\n if (/^\\s*import\\s+[\"']/m.test(source)) {\n throw new HostLoadError(\n `${file} contains a side-effect import — a host file may only import the project's powerhouse.config.json or sibling host files.`,\n );\n }\n if (/\\bimport\\s*\\(/.test(source) || /\\brequire\\s*\\(/.test(source)) {\n throw new HostLoadError(\n `${file} uses dynamic import()/require() — host files are static data.`,\n );\n }\n rejectProcessAccess(source, file);\n return imports;\n}\n\n/** {@link scanHostImports}, returning only the sibling host names (for cycle\n * detection). */\nexport function lintHostImports(rawSource: string, file: string): string[] {\n return scanHostImports(rawSource, file).hosts;\n}\n\n/** A generated `outputs.js` is plain data: no imports of any kind, no\n * dynamic import/require, no `process.`. */\nexport function lintOutputsFile(rawSource: string, file: string): void {\n const source = stripComments(rawSource);\n if (\n /^\\s*import\\b/m.test(source) ||\n /^\\s*export\\b[^;]*?\\bfrom\\s+[\"']/m.test(source) ||\n /\\bimport\\s*\\(/.test(source) ||\n /\\brequire\\s*\\(/.test(source)\n ) {\n throw new HostLoadError(\n `${file} imports a module — a generated ${OUTPUTS_FILE} is plain data.`,\n \"Regenerate it with `ph generate hosts` instead of editing it.\",\n );\n }\n rejectProcessAccess(source, file);\n}\n\n/** Walks the sibling-import graph from `hostName`, linting every visited file\n * (and every outputs.js it imports) and failing on a cycle (an ESM circular\n * would otherwise surface as an undefined default export with no useful\n * message). Returns the hosts whose outputs.js the graph imports, sorted. */\nexport function lintHostImportGraph(\n hostsDir: string,\n hostName: string,\n): string[] {\n const state = new Map<string, \"visiting\" | \"done\">();\n const producers = new Set<string>();\n const visit = (name: string, chain: string[]): void => {\n const mark = state.get(name);\n if (mark === \"done\") return;\n if (mark === \"visiting\") {\n throw new HostLoadError(\n `Host import cycle: ${[...chain, name].map((n) => `hosts/${n}`).join(\" -> \")}.`,\n \"Hoist the shared data into one host (or powerhouse.config.json) instead of importing both ways.\",\n );\n }\n const file = path.join(hostsDir, name, HOST_FILE);\n if (!existsSync(file)) {\n throw new HostLoadError(\n `hosts/${chain[chain.length - 1] ?? name} imports sibling \"hosts/${name}/host.js\", which does not exist.`,\n );\n }\n state.set(name, \"visiting\");\n const imports = scanHostImports(readFileSync(file, \"utf8\"), file);\n for (const producer of imports.outputs) {\n if (producers.has(producer)) continue;\n const outputsFile = path.join(hostsDir, producer, OUTPUTS_FILE);\n if (!existsSync(outputsFile)) {\n throw new HostLoadError(\n `hosts/${name}/host.js imports \"hosts/${producer}/${OUTPUTS_FILE}\", which does not exist.`,\n GENERATE_HINT,\n );\n }\n lintOutputsFile(readFileSync(outputsFile, \"utf8\"), outputsFile);\n producers.add(producer);\n }\n for (const sibling of imports.hosts) visit(sibling, [...chain, name]);\n state.set(name, \"done\");\n };\n visit(hostName, []);\n return [...producers].sort();\n}\n\n/** Returns the path of the first value that would not survive a JSON round\n * trip, or undefined when the object is fully static. */\nexport function findNonStaticValue(\n value: unknown,\n trail = \"\",\n): string | undefined {\n if (value === null) return undefined;\n const kind = typeof value;\n if (kind === \"string\" || kind === \"number\" || kind === \"boolean\") {\n return undefined;\n }\n if (kind !== \"object\") {\n return `${trail || \"<root>\"} (${kind})`;\n }\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const hit = findNonStaticValue(value[i], `${trail}[${i}]`);\n if (hit) return hit;\n }\n return undefined;\n }\n const proto: unknown = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) {\n return `${trail || \"<root>\"} (non-plain object)`;\n }\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n const hit = findNonStaticValue(child, trail ? `${trail}.${key}` : key);\n if (hit) return hit;\n }\n return undefined;\n}\n\nexport type { HostDefinition } from \"./host-schemas.js\";\n\nexport interface LoadedHost {\n name: string;\n dir: string;\n file: string;\n host: HostDefinition;\n}\n\nfunction assertHostShape(\n host: Record<string, unknown>,\n file: string,\n): asserts host is HostDefinition & Record<string, unknown> {\n if (typeof host.name !== \"string\" || host.name.length === 0) {\n throw new HostLoadError(`${file}: \\`name\\` must be a non-empty string.`);\n }\n const runner = host.runner;\n if (\n runner === null ||\n typeof runner !== \"object\" ||\n typeof (runner as Record<string, unknown>).module !== \"string\"\n ) {\n throw new HostLoadError(\n `${file}: \\`runner\\` must be an object with a \\`module\\` specifier string.`,\n );\n }\n if (host.reactor !== undefined && host.children !== undefined) {\n throw new HostLoadError(\n `${file}: \\`reactor\\` and \\`children\\` are mutually exclusive — a host is a reactor runner or a compound runner, never both.`,\n );\n }\n}\n\nexport async function loadHost(\n projectRoot: string,\n hostName: string,\n): Promise<LoadedHost> {\n return importHost(projectRoot, hostName, true);\n}\n\nasync function importHost(\n projectRoot: string,\n hostName: string,\n checkOutputs: boolean,\n): Promise<LoadedHost> {\n const probe = probeHostsFolder(projectRoot);\n if (probe.kind === \"absent\") {\n throw new HostLoadError(\n `No hosts/ folder found in ${projectRoot}.`,\n \"New projects get one from `ph init`; in an existing project, create hosts/<name>/host.js.\",\n );\n }\n if (probe.kind === \"empty\") {\n throw new HostLoadError(\n `hosts/ exists at ${probe.dir} but contains no <name>/host.js.`,\n \"An empty hosts/ folder defines no hosts; add a host definition or remove the folder.\",\n );\n }\n if (!probe.hosts.includes(hostName)) {\n throw new HostLoadError(\n `Unknown host \"${hostName}\". Available hosts: ${probe.hosts.join(\", \")}.`,\n );\n }\n\n const file = path.join(probe.dir, hostName, HOST_FILE);\n const producers = lintHostImportGraph(probe.dir, hostName);\n // Step 1 of the loader pipeline: a stale outputs.js fails before the host\n // is evaluated (its token tree may name outputs that no longer exist).\n if (checkOutputs) {\n for (const producer of producers) {\n await assertOutputsFileFresh(projectRoot, probe.dir, hostName, producer);\n }\n }\n\n const module = (await import(pathToFileURL(file).href)) as {\n default?: unknown;\n };\n const host = module.default;\n if (host === null || typeof host !== \"object\" || Array.isArray(host)) {\n throw new HostLoadError(\n `${file} must default-export the host object (\\`export default { name, runner, ... }\\`).`,\n );\n }\n\n const nonStatic = findNonStaticValue(host);\n if (nonStatic) {\n throw new HostLoadError(\n `${file} exports a non-static value at \\`${nonStatic}\\` — host files must survive a JSON round trip.`,\n \"Runtime behavior belongs in the runner; host files only carry data.\",\n );\n }\n\n assertHostShape(host as Record<string, unknown>, file);\n return {\n name: hostName,\n dir: path.dirname(file),\n file,\n host: host as HostDefinition,\n };\n}\n\n/* ---------------------------------------------------- generated outputs.js */\n\n/** What `ph generate hosts` derives a host's outputs.js from, plus the hash\n * of exactly those inputs (embedded in the file; the loader recomputes it). */\nexport interface HostOutputsDescription {\n /** The producer's folder name: the `host` of every `$output` token. */\n host: string;\n runnerModule: string;\n /** JSON Schema of the runner's `outputsSchema` (output side, no `$schema`). */\n outputsSchema: Record<string, unknown>;\n /** Declared LOCAL drive slugs: `reactor.drives` without remote drives,\n * plus drives the host's plugins contribute (any verb). Sorted, unique.\n * These are the known keys of the `drives` record output. */\n drives: string[];\n hash: string;\n}\n\nconst OUTPUTS_HASH_EXPORT = /^export const outputsHash = \"([^\"]+)\";$/m;\n\n/** The hash a generated outputs.js carries, or undefined. */\nexport function readOutputsFileHash(source: string): string | undefined {\n return OUTPUTS_HASH_EXPORT.exec(source)?.[1];\n}\n\nfunction canonicalJson(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map(canonicalJson).join(\",\")}]`;\n }\n if (value !== null && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, child]) => child !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`).join(\",\")}}`;\n }\n return JSON.stringify(value);\n}\n\n/** sha256 over the canonical JSON of the generator's inputs. The host name\n * is one: every token in the file carries it, so a copied or renamed host\n * folder makes its outputs.js stale. */\nexport function computeOutputsHash(input: {\n host: string;\n runnerModule: string;\n outputsSchema: Record<string, unknown>;\n drives: readonly string[];\n}): string {\n const digest = createHash(\"sha256\")\n .update(\n canonicalJson({\n v: 1,\n host: input.host,\n runnerModule: input.runnerModule,\n outputsSchema: input.outputsSchema,\n drives: [...new Set(input.drives)].sort(),\n }),\n )\n .digest(\"hex\");\n return `sha256:${digest.slice(0, 32)}`;\n}\n\nfunction isZodSchema(value: unknown): value is z.ZodType {\n return value !== null && typeof value === \"object\" && \"_zod\" in value;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/** Local (non-remote) slugs from a drive declaration list. */\nfunction localDriveSlugs(drives: unknown): string[] {\n if (!Array.isArray(drives)) return [];\n return drives.flatMap((drive) =>\n isRecord(drive) &&\n typeof drive.slug === \"string\" &&\n drive.remote === undefined\n ? [drive.slug]\n : [],\n );\n}\n\n/**\n * Describes the outputs a host's creation produces, for `ph generate hosts`\n * and the loader's staleness check: the runner's `outputsSchema` as JSON\n * Schema and the host's declared local drives (the keys `drives.<slug>` of a\n * switchboard-like runner). Returns undefined when the runner exports no\n * `outputsSchema` (the host produces nothing a token can reference).\n *\n * Plugin-contributed drives are collected across every verb (verb scoping\n * is ignored: a drive any verb serves is referenceable). Plugins the project\n * tree cannot resolve contribute nothing, exactly as at boot. The implicit\n * default drive a switchboard serves when it declares none is NOT a known\n * key (it is not declared); reach it with a literal `$output` token.\n */\nexport async function describeHostOutputs(\n projectRoot: string,\n hostName: string,\n): Promise<HostOutputsDescription | undefined> {\n const { host, file } = await importHost(projectRoot, hostName, false);\n const runnerModule = host.runner.module;\n const runner = await resolveRunnerModule(projectRoot, runnerModule);\n const schema = runner.outputsSchema;\n if (!isZodSchema(schema)) return undefined;\n const { $schema: _dialect, ...outputsSchema } = z.toJSONSchema(schema, {\n io: \"output\",\n unrepresentable: \"any\",\n }) as Record<string, unknown>;\n\n const reactor = (host as { reactor?: unknown }).reactor;\n const drives = localDriveSlugs(isRecord(reactor) ? reactor.drives : []);\n const entries: PluginEntryData[] = (host.runner.plugins ?? []).map((entry) =>\n typeof entry === \"string\" ? entry : { ...entry, verbs: \"*\" },\n );\n if (entries.length > 0) {\n const plan = await resolvePluginContributions(\n projectRoot,\n \"*\",\n entries,\n path.relative(projectRoot, file),\n );\n drives.push(\n ...localDriveSlugs(plan.drives.map((drive) => drive.declaration)),\n );\n }\n const sortedDrives = [...new Set(drives)].sort();\n return {\n host: hostName,\n runnerModule,\n outputsSchema,\n drives: sortedDrives,\n hash: computeOutputsHash({\n host: hostName,\n runnerModule,\n outputsSchema,\n drives: sortedDrives,\n }),\n };\n}\n\nasync function assertOutputsFileFresh(\n projectRoot: string,\n hostsDir: string,\n consumer: string,\n producer: string,\n): Promise<void> {\n const rel = `hosts/${producer}/${OUTPUTS_FILE}`;\n const actual = readOutputsFileHash(\n readFileSync(path.join(hostsDir, producer, OUTPUTS_FILE), \"utf8\"),\n );\n if (!existsSync(path.join(hostsDir, producer, HOST_FILE))) {\n throw new HostLoadError(\n `hosts/${consumer} imports ${rel}, but there is no hosts/${producer}/host.js to produce it.`,\n \"Delete the orphaned outputs.js and fix the import.\",\n );\n }\n const description = await describeHostOutputs(projectRoot, producer);\n if (!description) {\n throw new HostLoadError(\n `hosts/${consumer} imports ${rel}, but hosts/${producer}'s runner declares no outputsSchema, so it produces no outputs.`,\n );\n }\n if (actual !== description.hash) {\n throw new HostLoadError(\n `${rel} is stale (its producer's outputsSchema or declared drives changed since it was generated); run \\`ph generate hosts\\`.`,\n actual === undefined\n ? `${rel} carries no outputsHash export; it was not generated by \\`ph generate hosts\\`.`\n : `expected ${description.hash}, found ${actual}.`,\n );\n }\n}\n","import { RunnerError } from \"./runner-resolver.js\";\n\n/**\n * The arguments of one invocation: what follows `ph run <host> [verb]` and\n * `ph run` does not read itself. A runner declares the ones it accepts as its\n * `argsSchema` export; anything else fails before the runner starts.\n */\n\n/** The arguments a runner accepts, as typed (`--port`, `-w`). Structural: a\n * runner builds it from its own argument definitions, and this package needs\n * no argument parser. */\nexport interface RunnerArgsSchema {\n /** Take a value: `--port 4001` or `--port=4001`. */\n options: readonly string[];\n /** Switches: `--strictPort`. */\n flags: readonly string[];\n /** The name a compound's member takes an option under, e.g.\n * `{ \"--switchboard-port\": \"--port\" }`. In a compound the plain name is\n * refused: it would reach every member that has it. */\n memberOptions?: Readonly<Record<string, string>>;\n /** Retired switches and what to do instead: accepted, one warning, no\n * effect. */\n retired?: Readonly<Record<string, string>>;\n}\n\nconst isStrings = (value: unknown): value is readonly string[] =>\n Array.isArray(value) && value.every((item) => typeof item === \"string\");\n\nconst isStringRecord = (value: unknown): value is Record<string, string> =>\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.values(value).every((item) => typeof item === \"string\");\n\nexport function isRunnerArgsSchema(value: unknown): value is RunnerArgsSchema {\n if (typeof value !== \"object\" || value === null) return false;\n const schema = value as Record<string, unknown>;\n return (\n isStrings(schema.options) &&\n isStrings(schema.flags) &&\n (schema.memberOptions === undefined ||\n isStringRecord(schema.memberOptions)) &&\n (schema.retired === undefined || isStringRecord(schema.retired))\n );\n}\n\nexport interface SplitRunArgv {\n host?: string;\n verb?: string;\n /** `ph run`'s own arguments (`--debug`, `--stop`, `--explain <topic>`,\n * help). */\n own: string[];\n /** Everything else, in order: the runner's. */\n argv: string[];\n}\n\nconst OWN_FLAGS = new Set([\"--debug\", \"--stop\", \"--help\", \"-h\"]);\n\n/**\n * Splits what follows `ph run`. The host and the verb come before the\n * runner's arguments: `ph run` does not know which of those take a value, so\n * a bare word after the first of them belongs to the runner. A literal `--`\n * hands over everything after it.\n */\nexport function splitRunArgv(args: readonly string[]): SplitRunArgv {\n const result: SplitRunArgv = { own: [], argv: [] };\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === \"--\") {\n result.argv.push(...args.slice(i + 1));\n break;\n }\n if (OWN_FLAGS.has(arg) || arg.startsWith(\"--explain=\")) {\n result.own.push(arg);\n } else if (arg === \"--explain\") {\n result.own.push(...args.slice(i, i + 2));\n i++;\n } else if (arg.startsWith(\"-\") || result.argv.length > 0) {\n result.argv.push(arg);\n } else if (result.host === undefined) {\n result.host = arg;\n } else if (result.verb === undefined) {\n result.verb = arg;\n } else {\n result.argv.push(arg);\n }\n }\n return result;\n}\n\ninterface ArgvEntry {\n /** The argument as typed, without its value: `--port`. */\n name: string;\n /** Its tokens: `[\"--port\", \"4001\"]` or `[\"--port=4001\"]`. */\n tokens: string[];\n}\n\nfunction entriesOf(\n argv: readonly string[],\n takesValue: (name: string) => boolean,\n where: string,\n): ArgvEntry[] {\n const entries: ArgvEntry[] = [];\n for (let i = 0; i < argv.length; i++) {\n const token = argv[i];\n if (token === \"--\") continue;\n const equals = token.startsWith(\"-\") ? token.indexOf(\"=\") : -1;\n const name = equals === -1 ? token : token.slice(0, equals);\n if (equals === -1 && takesValue(name)) {\n if (i + 1 >= argv.length) {\n throw new RunnerError(`${where}: ${name} needs a value.`);\n }\n entries.push({ name, tokens: [token, argv[i + 1]] });\n i++;\n } else {\n entries.push({ name, tokens: [token] });\n }\n }\n return entries;\n}\n\nfunction warnRetired(name: string, instead: string): void {\n console.warn(`${name} is retired and has no effect: ${instead}`);\n}\n\nconst acceptedBy = (schema: RunnerArgsSchema): string[] => [\n ...schema.options,\n ...schema.flags,\n];\n\nexport interface RunnerArgvTarget {\n /** The host's folder name under hosts/. */\n host: string;\n /** The runner's specifier. */\n runner: string;\n /** The runner module's `argsSchema` export. */\n schema: unknown;\n}\n\n/**\n * The arguments a standalone runner receives as `ctx.argv`: `argv` checked\n * against the runner's schema, retired switches warned about and dropped.\n * Nothing is dropped silently: an argument the runner does not accept, or any\n * argument for a runner without a schema, fails.\n */\nexport function checkRunnerArgv(\n argv: readonly string[],\n target: RunnerArgvTarget,\n): string[] {\n if (argv.length === 0) return [];\n const where = `hosts/${target.host}`;\n const schema = target.schema;\n if (!isRunnerArgsSchema(schema)) {\n throw new RunnerError(\n `${where}: its runner ${target.runner} accepts no arguments, but got: ${argv.join(\" \")}`,\n \"Set these in the host file instead.\",\n );\n }\n const options = new Set(schema.options);\n const accepted = new Set(acceptedBy(schema));\n const kept: string[] = [];\n const unknown: string[] = [];\n for (const entry of entriesOf(argv, (name) => options.has(name), where)) {\n const instead = schema.retired?.[entry.name];\n if (accepted.has(entry.name)) {\n kept.push(...entry.tokens);\n } else if (instead !== undefined) {\n warnRetired(entry.name, instead);\n } else {\n unknown.push(entry.name);\n }\n }\n if (unknown.length > 0) {\n throw new RunnerError(\n `${where}: its runner ${target.runner} does not accept ${unknown.join(\", \")}.`,\n `It accepts: ${[...accepted].join(\", \") || \"no arguments\"}.`,\n );\n }\n return kept;\n}\n\nexport interface CompoundArgvMember {\n /** The member's key in the compound's `children`. */\n key: string;\n /** The member runner's specifier. */\n runner: string;\n /** The member runner module's `argsSchema` export. */\n schema: unknown;\n}\n\n/**\n * A compound's arguments, per member key: each member gets the ones its\n * runner accepts. A member option arrives under its member name\n * (`--switchboard-port 4001` reaches that member as `--port 4001`). An\n * argument no member accepts fails, as does one that would set the same\n * option on several members.\n */\nexport function splitCompoundArgv(\n argv: readonly string[],\n host: string,\n members: readonly CompoundArgvMember[],\n): Map<string, string[]> {\n const perMember = new Map<string, string[]>(members.map((m) => [m.key, []]));\n if (argv.length === 0) return perMember;\n const where = `hosts/${host}`;\n const schemas = members.flatMap((m) =>\n isRunnerArgsSchema(m.schema) ? [{ key: m.key, schema: m.schema }] : [],\n );\n // plain option name -> the member names it goes by\n const memberNames = new Map<string, string[]>();\n for (const { schema } of schemas) {\n for (const [alias, option] of Object.entries(schema.memberOptions ?? {})) {\n const aliases = memberNames.get(option) ?? [];\n if (!aliases.includes(alias)) aliases.push(alias);\n memberNames.set(option, aliases);\n }\n }\n const takesValue = (name: string) =>\n schemas.some(\n ({ schema }) =>\n schema.options.includes(name) ||\n schema.memberOptions?.[name] !== undefined,\n );\n const warned = new Set<string>();\n const unknown: string[] = [];\n for (const entry of entriesOf(argv, takesValue, where)) {\n const { name, tokens } = entry;\n const named = schemas.filter(\n ({ schema }) => schema.memberOptions?.[name] !== undefined,\n );\n if (named.length > 1) {\n throw new RunnerError(\n `${where}: ${name} matches the members ${named.map((m) => m.key).join(\", \")}.`,\n \"Set the option in each member's host file instead.\",\n );\n }\n if (named.length === 1) {\n const { key, schema } = named[0];\n const option = schema.memberOptions?.[name] ?? name;\n // `--switchboard-port=4001` keeps its `=4001`\n const first = option + tokens[0].slice(name.length);\n perMember.get(key)?.push(first, ...tokens.slice(1));\n continue;\n }\n const aliases = memberNames.get(name);\n if (aliases) {\n throw new RunnerError(\n `${where}: ${name} does not say which member it is for.`,\n `Use ${aliases.join(\" or \")}.`,\n );\n }\n const takers = schemas.filter(({ schema }) =>\n acceptedBy(schema).includes(name),\n );\n if (takers.length > 0) {\n for (const { key } of takers) perMember.get(key)?.push(...tokens);\n continue;\n }\n const retired = schemas.find(\n ({ schema }) => schema.retired?.[name] !== undefined,\n );\n if (retired) {\n if (!warned.has(name)) {\n warned.add(name);\n warnRetired(name, retired.schema.retired?.[name] ?? \"\");\n }\n continue;\n }\n unknown.push(name);\n }\n if (unknown.length > 0) {\n const accepted = members.map((m) => {\n if (!isRunnerArgsSchema(m.schema)) {\n return ` - ${m.key} (${m.runner}): no arguments`;\n }\n const schema = m.schema;\n const scoped = new Set(Object.values(schema.memberOptions ?? {}));\n const names = [\n ...Object.keys(schema.memberOptions ?? {}),\n ...acceptedBy(schema).filter((name) => !scoped.has(name)),\n ];\n return ` - ${m.key} (${m.runner}): ${names.join(\", \") || \"no arguments\"}`;\n });\n throw new RunnerError(\n `${where}: no member accepts ${unknown.join(\", \")}. The members accept:\\n${accepted.join(\"\\n\")}`,\n );\n }\n return perMember;\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 { resolvePhDir } from \"@powerhousedao/shared/clis/ph-dir\";\nimport { execFileSync } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { HOST_NAME_MESSAGE, hostNameSchema } from \"./host-schemas.js\";\nimport { runRecordSchema, type RunRecord } from \"./run-record-schema.js\";\n\nexport {\n runRecordMemberSchema,\n runRecordSchema,\n type RunRecord,\n type RunRecordMember,\n} from \"./run-record-schema.js\";\n\n/**\n * Record I/O for `.ph/run/<host>.json`, keyed by host name so N hosts\n * (vetra, desktop, …) coexist. The record shape is run-record-schema.ts (v2).\n */\n\nexport type RunProbe =\n | { status: \"none\" }\n | { status: \"stale\"; record: RunRecord }\n | { status: \"live\"; record: RunRecord }\n | { status: \"foreign\"; record: RunRecord };\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\n// Under the project's .ph tree — relocated with it by PH_USER_DATA_DIR. The\n// readers take `env` so a launcher can read a child's records.\nconst runDir = (projectDir: string, env: Env = process.env) =>\n path.join(resolvePhDir(projectDir, env), \"run\");\nfunction recordPath(projectDir: string, hostName: string, env?: Env): string {\n const dir = runDir(projectDir, env);\n const file = path.resolve(dir, `${hostName}.json`);\n if (\n !hostNameSchema.safeParse(hostName).success ||\n path.dirname(file) !== path.resolve(dir)\n ) {\n throw new Error(\n `\"${hostName}\" can't name a run record. ${HOST_NAME_MESSAGE}`,\n );\n }\n return file;\n}\n\nexport function readRunRecord(\n projectDir: string,\n hostName: string,\n env: Env = process.env,\n): RunRecord | undefined {\n let raw: unknown;\n try {\n raw = JSON.parse(\n fs.readFileSync(recordPath(projectDir, hostName, env), \"utf8\"),\n );\n } catch {\n return undefined;\n }\n // v1 and foreign-shaped records read as \"not running\" (3.6).\n const parsed = runRecordSchema.safeParse(raw);\n return parsed.success ? parsed.data : undefined;\n}\n\n/** Every valid v2 record under `.ph/run/` (invalid and v1 files skipped). */\nexport function listRunRecords(\n projectDir: string,\n env: Env = process.env,\n): RunRecord[] {\n let files: string[];\n try {\n files = fs.readdirSync(runDir(projectDir, env));\n } catch {\n return [];\n }\n return files\n .filter((file) => file.endsWith(\".json\"))\n .flatMap((file) => {\n const record = readRunRecord(\n projectDir,\n file.slice(0, -\".json\".length),\n env,\n );\n return record ? [record] : [];\n });\n}\n\n/** The project identity the live/foreign probe compares: package.json\n * `name`, else the folder name. */\nexport function readProjectName(projectDir: string): string {\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(projectDir, \"package.json\"), \"utf8\"),\n ) as { name?: unknown };\n if (typeof pkg.name === \"string\" && pkg.name) return pkg.name;\n } catch {\n // fall through\n }\n return path.basename(path.resolve(projectDir));\n}\n\nexport function writeRunRecord(projectDir: string, record: RunRecord): void {\n const target = recordPath(projectDir, record.host);\n const valid = runRecordSchema.parse(record);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, `${JSON.stringify(valid, null, 2)}\\n`);\n}\n\nexport function clearRunRecord(\n projectDir: string,\n hostName: string,\n env: Env = process.env,\n): void {\n try {\n fs.rmSync(recordPath(projectDir, hostName, env));\n } catch {\n // already gone\n }\n}\n\nexport function isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM = the process exists but belongs to another user.\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/** When a process started, in ms since the epoch; undefined when the\n * platform does not tell (the process is gone, the tool is missing). */\nexport function processStartedAtMs(pid: number): number | undefined {\n try {\n if (process.platform === \"linux\") {\n // Field 22 of /proc/<pid>/stat: start in clock ticks (100 a second)\n // after boot; the command (field 2) may hold spaces, so count from\n // its closing bracket.\n const stat = fs.readFileSync(`/proc/${pid}/stat`, \"utf8\");\n const ticks = Number(\n stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \")[19],\n );\n const boot = /^btime (\\d+)$/m.exec(fs.readFileSync(\"/proc/stat\", \"utf8\"));\n if (!boot || !Number.isFinite(ticks)) return undefined;\n return (Number(boot[1]) + ticks / 100) * 1000;\n }\n const [command, args] =\n process.platform === \"win32\"\n ? [\n \"powershell.exe\",\n [\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-Command\",\n `(Get-Process -Id ${pid}).StartTime.ToUniversalTime().ToString('o')`,\n ],\n ]\n : [\"ps\", [\"-o\", \"lstart=\", \"-p\", String(pid)]];\n const out = execFileSync(command, args, {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: 10_000,\n windowsHide: true,\n env: { ...process.env, LC_ALL: \"C\" },\n }).trim();\n const started = Date.parse(out);\n return Number.isFinite(started) ? started : undefined;\n } catch {\n return undefined;\n }\n}\n\n// A record is written by the process it names, so that process started\n// before `startedAt`. The slack covers clocks that count in seconds.\nconst START_SLACK_MS = 5_000;\n// The records whose pid was found to be the recording process: asked once\n// per record, since the answer costs a child process on Windows and macOS.\nconst confirmedRecords = new Set<string>();\n\n/** True when the recorded pid now names another process: one that started\n * after the record was written. False when that cannot be told. */\nfunction isPidReused(record: RunRecord): boolean {\n if (record.pid === process.pid) return false;\n const recordedAt = Date.parse(record.startedAt);\n if (!Number.isFinite(recordedAt)) return false;\n const key = `${record.pid}:${record.startedAt}`;\n if (confirmedRecords.has(key)) return false;\n const startedAt = processStartedAtMs(record.pid);\n if (startedAt === undefined) return false;\n if (startedAt > recordedAt + START_SLACK_MS) return true;\n confirmedRecords.add(key);\n return false;\n}\n\n/**\n * Decide whether the recorded instance is this project's live host.\n *\n * pid liveness alone proves nothing (pids are reused): a live pid counts\n * only when its process started before the record was written. The recorded\n * projectName is what separates \"my instance\" from \"a different project that\n * happens to hold this storage root\" — the confusion the vetra lock exists to\n * prevent. A stale record (dead or reused pid) is reported so the caller can\n * clear it; a foreign one (live pid, different project) is left alone.\n */\nexport function probeRun(\n projectDir: string,\n hostName: string,\n projectName: string,\n env: Env = process.env,\n): RunProbe {\n const record = readRunRecord(projectDir, hostName, env);\n if (!record) return { status: \"none\" };\n if (!isPidAlive(record.pid) || isPidReused(record)) {\n return { status: \"stale\", record };\n }\n if (record.projectName !== projectName) return { status: \"foreign\", record };\n return { status: \"live\", record };\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 path from \"node:path\";\nimport { substituteBuiltinEnv } from \"./env-substitution.js\";\n\n/**\n * `${userData}` resolution for host files (desktop shape): storage paths in a\n * host must not derive from the instance name (renames must stay safe), so\n * the host file writes `${userData}/.ph/reactor-storage` and the RUNNER\n * resolves it at start. `${userData}` is a PROJECT-SHAPED root: its `.ph`\n * subtree carries the same names the classic commands use under\n * `<project>/.ph` (see `resolvePhDir`). In the CLI it IS the project root, so\n * `ph run desktop` in a project shares the one `.ph` tree `ph vetra` uses;\n * a shell (Tauri) points it at the OS profile via PH_USER_DATA_DIR, and the\n * whole `.ph` tree — stores, identity, run records — follows.\n */\nexport function defaultUserDataDir(\n projectRoot: string,\n env: Record<string, string | undefined> = process.env,\n): string {\n return env.PH_USER_DATA_DIR ?? path.resolve(projectRoot);\n}\n\n/** Deep-substitute `${userData}` in every string of a JSON-shaped value.\n * Non-strings pass through; the input is never mutated. */\nexport function resolveUserDataPlaceholders<T>(value: T, userData: string): T {\n return substituteBuiltinEnv(value, { userData });\n}\n","import path from \"node:path\";\nimport { loadHost } from \"../host-loader.js\";\nimport { defaultUserDataDir } from \"../placeholders.js\";\nimport { isPidAlive, listRunRecords, probeRun } from \"../run-record.js\";\nimport { resolveRunnerModule, type RunnerModule } from \"../runner-resolver.js\";\nimport type { OutputRef, OutputsSchemaLookup } from \"./declared.js\";\nimport type { OutputSource, ResolveSources } from \"./resolve.js\";\n\n/**\n * Node adapters for the resolver: producer discovery (a token names a host\n * by FOLDER; run records are keyed by the host's `name`, so the producer's\n * host.js is loaded to map one to the other), the standalone run-record\n * output source, and the process environment.\n */\n\nexport interface ProducerInfo {\n /** The folder a token names (`hosts/<folder>/`). */\n folder: string;\n /** The producer host's `name` (its run-record key). */\n name: string;\n specifier: string;\n runner: RunnerModule;\n}\n\n/** Producers by folder; a folder that fails to load carries its error. */\nexport type ProducerMap = ReadonlyMap<string, ProducerInfo | { error: string }>;\n\n/** Load every producer host a set of refs names (each once). */\nexport async function loadProducers(\n projectRoot: string,\n refs: readonly OutputRef[],\n): Promise<ProducerMap> {\n const producers = new Map<string, ProducerInfo | { error: string }>();\n for (const { host: folder } of refs) {\n if (producers.has(folder)) continue;\n try {\n const loaded = await loadHost(projectRoot, folder);\n const specifier = loaded.host.runner.module;\n producers.set(folder, {\n folder,\n name: loaded.host.name,\n specifier,\n runner: await resolveRunnerModule(projectRoot, specifier),\n });\n } catch (error) {\n producers.set(folder, {\n error: `names host \"${folder}\", which cannot be loaded: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n }\n return producers;\n}\n\n/** The outputs schema of a runner module, or why it has none. */\nexport function runnerOutputsSchema(\n runner: RunnerModule,\n specifier: string,\n label: string,\n): OutputsSchemaLookup {\n const schema = runner.outputsSchema;\n if (schema === undefined || schema === null) {\n return {\n error: `${label} runs \"${specifier}\", which exports no outputsSchema, so it produces no outputs a token can read.`,\n };\n }\n return { schema, label: `\"${specifier}\" (${label})` };\n}\n\n/** Declared-validation lookup for a standalone host's producers. */\nexport function producerOutputsSchemas(\n producers: ProducerMap,\n): (ref: OutputRef) => OutputsSchemaLookup {\n return (ref) => {\n const info = producers.get(ref.host);\n if (!info)\n return { error: `names host \"${ref.host}\", which was not loaded.` };\n if (\"error\" in info) return { error: info.error };\n return runnerOutputsSchema(\n info.runner,\n info.specifier,\n `host \"${ref.host}\"`,\n );\n };\n}\n\n/** Further `.ph` roots whose live run records a standalone `$output` reads\n * (`path.delimiter`-separated): a launcher that gives each child its own\n * PH_USER_DATA_DIR names its siblings' here. Locks never read them. */\nexport const OUTPUT_DATA_DIRS_ENV = \"PH_OUTPUT_DATA_DIRS\";\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\n/** The other roots, each once, never the process's own. */\nfunction siblingEnvs(projectRoot: string, env: Env): Env[] {\n const own = path.resolve(defaultUserDataDir(projectRoot, env));\n const dirs = new Set(\n (env[OUTPUT_DATA_DIRS_ENV] ?? \"\")\n .split(path.delimiter)\n .filter((dir) => dir !== \"\")\n .map((dir) => path.resolve(dir)),\n );\n return [...dirs]\n .filter((dir) => dir !== own)\n .map((dir) => ({ PH_USER_DATA_DIR: dir }));\n}\n\n/**\n * Standalone `$output` source: the producer's live v2 run record. Its own\n * standalone record under the process's `.ph` root first (keyed by the\n * producer's `name`); else exactly one of: a standalone record under a\n * PH_OUTPUT_DATA_DIRS root, or a member running that host in a live compound\n * of this project under any root. A missing, stale, foreign or output-less\n * record means \"not running\", and the lookup fails naming the producer and\n * how to start it (no fallback to the producer's declared config, no\n * waiting).\n */\nexport function runRecordOutputSource(\n projectRoot: string,\n options: {\n consumer: string;\n producers: ProducerMap;\n projectName: string;\n env?: Env;\n },\n): OutputSource {\n const { consumer, producers, projectName } = options;\n const env = options.env ?? process.env;\n const siblings = siblingEnvs(projectRoot, env);\n return {\n lookup(ref) {\n const notRunning = `${consumer} needs outputs from host \"${ref.host}\", which is not running. Start it first: ph run ${ref.host} (or run a compound that includes it).`;\n const info = producers.get(ref.host);\n // The producer's outputsSchema: an absent optional field omits the\n // consuming property instead of failing.\n const schema =\n info && !(\"error\" in info) ? info.runner.outputsSchema : undefined;\n const withSchema =\n schema !== undefined && schema !== null ? { schema } : {};\n const standalone: { label: string; outputs: Record<string, unknown> }[] =\n [];\n if (ref.member === undefined && info && !(\"error\" in info)) {\n const probe = probeRun(projectRoot, info.name, projectName, env);\n if (probe.status === \"live\" && probe.record.outputs) {\n return {\n status: \"available\",\n outputs: probe.record.outputs,\n ...withSchema,\n };\n }\n for (const sibling of siblings) {\n const other = probeRun(projectRoot, info.name, projectName, sibling);\n if (other.status === \"live\" && other.record.outputs) {\n standalone.push({\n label: `\"${info.name}\" (pid ${other.record.pid})`,\n outputs: other.record.outputs,\n });\n }\n }\n }\n const members = [env, ...siblings]\n .flatMap((root) => listRunRecords(projectRoot, root))\n .filter(\n (record) =>\n record.members !== undefined &&\n record.projectName === projectName &&\n isPidAlive(record.pid),\n )\n .flatMap((record) =>\n Object.entries(record.members ?? {})\n .filter(\n ([key, member]) =>\n member.host === ref.host &&\n (ref.member === undefined || key === ref.member),\n )\n .map(([key, member]) => ({\n label: `member \"${key}\" of \"${record.host}\"`,\n outputs: member.outputs,\n })),\n );\n const found = [...standalone, ...members];\n if (found.length === 1) {\n return {\n status: \"available\",\n outputs: found[0].outputs,\n ...withSchema,\n };\n }\n if (found.length > 1) {\n return {\n status: \"unavailable\",\n message: `${consumer} needs outputs from host \"${ref.host}\", which runs as ${found.map((m) => m.label).join(\" and \")}; stop all but one, or run ${ref.host} on its own.`,\n };\n }\n return { status: \"unavailable\", message: notRunning };\n },\n };\n}\n\n/** The resolving process's `$env` inputs: its environment plus the\n * always-resolvable built-ins (`userData` honours PH_USER_DATA_DIR). */\nexport function processResolveEnv(\n projectRoot: string,\n env: Readonly<Record<string, string | undefined>> = process.env,\n): Pick<ResolveSources, \"env\" | \"builtins\"> {\n return {\n env,\n builtins: {\n userData: defaultUserDataDir(projectRoot, env),\n projectRoot: path.resolve(projectRoot),\n },\n };\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 { z } from \"zod\";\n\n/**\n * What a server verb returns to its supervisor (typed-host-configs 3.1/3.6):\n * `RunnerHandle<O>`. Consumers read a started host only through `outputs`\n * (and `$output` tokens over them). A verb that returns nothing (one-shot,\n * or self-sustaining) is an empty handle.\n */\nexport interface RunnerHandle<O = Record<string, unknown>> {\n outputs: O;\n /** Resolves when the member is serving. */\n ready: Promise<void>;\n /** Reverse-order compound teardown (and standalone signal handling). */\n shutdown(): Promise<void>;\n}\n\n/** The data half of a handle, validated by the compound. `ready`/`shutdown`\n * are functions and promises, so they are checked as TS fields, not here. */\nexport const runnerHandleSchema = z.looseObject({\n outputs: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type RunnerHandleData = z.infer<typeof runnerHandleSchema>;\n\n/** A verb's return value, normalized: validated data plus the live fields\n * when present. */\nexport interface StartedHandle extends RunnerHandleData {\n outputs: Record<string, unknown>;\n ready?: PromiseLike<unknown>;\n shutdown?: () => unknown;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return isRecord(value) && typeof value.then === \"function\";\n}\n\nfunction isCallable(value: unknown): value is (this: unknown) => unknown {\n return typeof value === \"function\";\n}\n\n/** Normalize what a verb returned. `undefined` (a self-sustaining bridge)\n * is an empty handle; anything else must match runnerHandleSchema. */\nexport function toStartedHandle(value: unknown, where: string): StartedHandle {\n if (value === undefined || value === null) return { outputs: {} };\n const parsed = runnerHandleSchema.safeParse(value);\n if (!parsed.success) {\n throw new Error(\n `${where} returned an invalid runner handle:\\n${z.prettifyError(parsed.error)}`,\n );\n }\n const live = isRecord(value) ? value : {};\n const shutdown = live.shutdown;\n return {\n ...parsed.data,\n outputs: parsed.data.outputs ?? {},\n ...(isPromiseLike(live.ready) ? { ready: live.ready } : {}),\n ...(isCallable(shutdown) ? { shutdown: () => shutdown.call(value) } : {}),\n };\n}\n","import { z } from \"zod\";\nimport {\n declaredGenericCompoundHostSchema,\n type ChildWrapper,\n type CompoundWiring,\n type HostDefinition,\n type RunnerKind,\n} from \"./host-schemas.js\";\nimport { applyChildWrapper, type MemberDraft } from \"./child-wrapper.js\";\nimport { substituteBuiltinEnv } from \"./env-substitution.js\";\nimport { loadHost } from \"./host-loader.js\";\nimport { declaresKey, outputSitesOf } from \"./resolve/declared.js\";\nimport { processResolveEnv, runnerOutputsSchema } from \"./resolve/node.js\";\nimport { memberForRef, planCompound } from \"./resolve/plan.js\";\nimport { findRemovedForms } from \"./resolve/removed-forms.js\";\nimport { isPlainObject } from \"./resolve/walk.js\";\nimport { emptyMaps, resolveHostOutputs } from \"./resolve/resolve.js\";\nimport { compoundOutputSource } from \"./resolve/sources.js\";\nimport {\n clearRunRecord,\n probeRun,\n writeRunRecord,\n type RunRecordMember,\n} from \"./run-record.js\";\nimport { splitCompoundArgv } from \"./runner-args.js\";\nimport { toStartedHandle, type StartedHandle } from \"./runner-handle.js\";\nimport {\n CONNECT_RUNNER,\n getVerb,\n isSchemaLike,\n ONE_SHOT_VERBS,\n resolveRunnerModule,\n RunnerError,\n validateDeclaredHost,\n validateHost,\n type RunnerContext,\n type RunnerModule,\n} from \"./runner-resolver.js\";\n\nexport type { MemberDraft } from \"./child-wrapper.js\";\nexport type { ChildWrapper, CompoundWiring } from \"./host-schemas.js\";\nexport type { RunnerHandle, StartedHandle } from \"./runner-handle.js\";\n\n/**\n * The generic compound runner: supervises the members a compound host\n * declares, each started via its OWN declared runner at its own effective\n * verb, writes a v2 .ph/run/<host>.json record, holds a per-project lock\n * (neither at a one-shot verb such as build, which starts nothing), and\n * tears members down in reverse order through their `shutdown()`.\n *\n * Members consume each other's outputs through `$output` tokens: the\n * dependency plan (resolve/plan.ts) orders the start, each member's tokens\n * resolve against the live outputs of the members started before it, and\n * the member's runner validates the resolved host.\n *\n * Attached and in-process: member verbs start their servers (which hold the\n * event loop) and return a handle; the compound lives as long as they do.\n */\n\ninterface StartedMember {\n name: string;\n member: ChildWrapper;\n specifier: string;\n kind: RunnerKind;\n verb: string;\n handle: StartedHandle;\n /** The outputs consumers read and the record holds: the handle's outputs\n * as parsed by the member runner's outputsSchema. */\n outputs: Record<string, unknown>;\n}\n\nexport interface PreparedMember {\n key: string;\n member: ChildWrapper;\n draft: MemberDraft;\n specifier: string;\n runner: RunnerModule;\n file: string;\n}\n\nexport async function memberDraft(\n projectRoot: string,\n member: ChildWrapper,\n): Promise<MemberDraft> {\n return applyChildWrapper(\n (await loadHost(projectRoot, member.host)).host,\n member,\n );\n}\n\n/** Whether a member receives the compound's `cspRegistrySync` wiring (as\n * `runner.cspRegistrySync`): its runner declares that option (any specifier\n * that reaches the Connect runner), or it names the Connect runner. A\n * member's role is its runner, not its folder. */\nexport function takesCspRegistrySync(m: PreparedMember): boolean {\n return (\n m.specifier === CONNECT_RUNNER ||\n declaresKey(m.runner.hostSchema, [\"runner\"], \"cspRegistrySync\")\n );\n}\n\nexport interface RunCompoundOptions {\n /** Project identity for the lock (defaults read from package.json by the CLI). */\n projectName: string;\n /** Extra record fields (e.g. mcpUrl). */\n recordExtra?: Record<string, unknown>;\n /** Registers the SIGINT/SIGTERM handlers (default true; tests pass false\n * and call `handleSignal`). */\n installSignalHandlers?: boolean;\n /** How the compound exits after a signal (default `process.exit`). */\n exit?: (code: number) => void;\n /** Stops the compound as SIGTERM would, once this delivers anything or\n * ends: see {@link stopStreamOf}. */\n stopStream?: NodeJS.ReadableStream;\n /** How long a stream's stop may take before exiting regardless (default\n * {@link STOP_STREAM_LIMIT_MS}). */\n stopStreamLimitMs?: number;\n /** What a stream's supervisor reads (default stdout and stderr). */\n supervisedOutputs?: readonly NodeJS.WritableStream[];\n}\n\n/** Set by a supervisor that holds this process's stdin. */\nexport const STOP_ON_STDIN_ENV = \"PH_STOP_ON_STDIN\";\n\n/** Past the shell's own limit: this only matters when no shell is left. */\nexport const STOP_STREAM_LIMIT_MS = 15_000;\n\n/**\n * Windows has no SIGTERM, so a supervisor asks a stack to stop through its\n * stdin: a line, or the pipe closing, which also covers the supervisor dying.\n * Only when it asks to: a stack started from a script may have no stdin.\n */\nexport function stopStreamOf(\n env: NodeJS.ProcessEnv,\n stdin: () => NodeJS.ReadableStream,\n): NodeJS.ReadableStream | undefined {\n return env[STOP_ON_STDIN_ENV] === \"1\" ? stdin() : undefined;\n}\n\nfunction whenStreamStops(stream: NodeJS.ReadableStream, stop: () => void) {\n let stopped = false;\n const once = () => {\n if (stopped) return;\n stopped = true;\n stop();\n };\n for (const event of [\"data\", \"end\", \"close\", \"error\"]) {\n stream.once(event, once);\n }\n stream.resume();\n}\n\nexport interface RunCompoundResult {\n started: StartedMember[];\n /** Graceful teardown, consumers before producers (reverse dependency\n * order); memoized. */\n shutdown: () => Promise<void>;\n /** What the compound's signal handlers run: the first signal shuts the\n * members down and exits once (130 / 143); later signals are ignored\n * while that teardown runs. */\n handleSignal: (signal: \"SIGINT\" | \"SIGTERM\") => Promise<void>;\n}\n\n/** The verb the generic compound starts its members at for its own `verb`:\n * `run` follows the compound's defaultVerb. */\nexport function compoundStartVerb(\n verb: string,\n runner: { defaultVerb?: string },\n): string {\n return verb === \"run\" ? (runner.defaultVerb ?? \"run\") : verb;\n}\n\n/** At compound verb \"run\" each member runs its own (merged) defaultVerb —\n * what lets a desktop compound pair a switchboard at `run` with a connect at\n * `serve`. An explicit forwarded verb stays uniform across members. */\nexport function memberVerbOf(\n compoundVerb: string,\n runner: { defaultVerb?: string },\n): string {\n return compoundVerb === \"run\" ? (runner.defaultVerb ?? \"run\") : compoundVerb;\n}\n\nexport async function runCompound(\n hostInput: HostDefinition,\n ctx: RunnerContext,\n options: RunCompoundOptions,\n): Promise<RunCompoundResult> {\n const compoundFile = `hosts/${hostInput.name}`;\n const removed = findRemovedForms(hostInput);\n if (removed.length > 0) {\n throw new RunnerError(\n `${compoundFile}: removed form:\\n${removed.map((r) => ` - ${r.path}: ${r.message}`).join(\"\\n\")}`,\n );\n }\n // Declared form: member wrappers may hold tokens (resolved per member).\n const parsed = declaredGenericCompoundHostSchema.safeParse(hostInput);\n if (!parsed.success) {\n throw new Error(\n `${compoundFile}: invalid compound host:\\n${z.prettifyError(parsed.error)}`,\n );\n }\n const host = parsed.data;\n const projectRoot = ctx.projectRoot;\n const wiring: CompoundWiring = host.config ?? {};\n // Resolved by the calling runner module: its `run` maps to defaultVerb.\n const verb = ctx.verb;\n // A one-shot compound verb (build) starts nothing: no lock, and no record\n // to write or clear (clearing would delete a live instance's record).\n const oneShotCompound = ONE_SHOT_VERBS.has(verb);\n const keepsRecord = wiring.runtimeRecord !== false && !oneShotCompound;\n\n // From the start, so a stop during boot takes effect when boot finishes.\n let stopRequested = false;\n let stopFromStream: () => void = () => {\n stopRequested = true;\n };\n if (options.stopStream && !oneShotCompound) {\n whenStreamStops(options.stopStream, () => stopFromStream());\n // These go when the supervisor does, and with no listener the next log\n // line would be a fatal error in the middle of the shutdown it started.\n const outputs = options.supervisedOutputs ?? [\n process.stdout,\n process.stderr,\n ];\n for (const output of outputs) output.on(\"error\", () => undefined);\n }\n\n // Lock: one live instance per project per host (storage-root contention).\n const probe = oneShotCompound\n ? undefined\n : probeRun(projectRoot, host.name, options.projectName);\n if (probe?.status === \"live\") {\n throw new Error(\n `${host.name} is already running for this project (pid ${probe.record.pid}). ` +\n `Stop it before starting another.`,\n );\n }\n if (probe?.status === \"foreign\") {\n throw new Error(\n `.ph/run/${host.name}.json describes a live \"${probe.record.projectName}\", ` +\n `but this project is \"${options.projectName}\". Refusing to start a second instance.`,\n );\n }\n // stale record: proceed (a dead pid does not hold the lock)\n\n // Declared phase: every member's draft, runner and tokens, before any\n // member starts — a bad token or order fails with nothing running.\n const prepared = await prepareMembers(projectRoot, host.children);\n const plan = planCompound(\n prepared.map((m) => ({\n key: m.key,\n host: m.member.host,\n refs: outputSitesOf(m.draft).map(({ ref, path }) => ({ ref, path })),\n })),\n wiring.startOrder,\n );\n const byKey = new Map(prepared.map((m) => [m.key, m]));\n const members = prepared.map((m) => ({ key: m.key, host: m.member.host }));\n for (const m of prepared) {\n validateDeclaredHost(m.runner, m.specifier, m.draft, m.file, {\n outputsSchemaOf: (ref) => {\n const target = memberForRef(ref, members);\n if (\"error\" in target) return { error: target.error };\n const producer = byKey.get(target.key);\n return producer\n ? runnerOutputsSchema(\n producer.runner,\n producer.specifier,\n `member \"${target.key}\"`,\n )\n : { error: `names member \"${target.key}\", which was not prepared.` };\n },\n });\n }\n\n // This invocation's arguments, per member: one no member accepts fails\n // with nothing running.\n const memberArgv = splitCompoundArgv(\n ctx.argv ?? [],\n hostInput.name,\n prepared.map((m) => ({\n key: m.key,\n runner: m.specifier,\n schema: m.runner.argsSchema,\n })),\n );\n\n if (wiring.cspRegistrySync && !prepared.some(takesCspRegistrySync)) {\n console.warn(\n `${compoundFile}: config.cspRegistrySync is set, but no member's runner declares runner.cspRegistrySync (members run: ${prepared.map((m) => m.specifier).join(\", \")}); the baked Connect CSP is not patched for the runtime registry.`,\n );\n }\n\n const started: StartedMember[] = [];\n const liveOutputs = new Map<string, Record<string, unknown>>();\n const outputs = compoundOutputSource(\n members,\n liveOutputs,\n host.name,\n new Map(prepared.map((m) => [m.key, m.runner.outputsSchema])),\n );\n const resolveEnv = processResolveEnv(projectRoot, ctx.env);\n\n // Members start in plan order (producers first), so the reverse is\n // reverse dependency order: a consumer stops before what it reads.\n let stopping: Promise<void> | undefined;\n const shutdown = () =>\n (stopping ??= (async () => {\n for (const m of [...started].reverse()) {\n try {\n await m.handle.shutdown?.();\n } catch {\n // best effort — keep tearing down the rest\n }\n }\n if (keepsRecord) clearRunRecord(projectRoot, host.name);\n })());\n\n try {\n for (const name of plan.order) {\n const m = byKey.get(name);\n if (!m) continue;\n const memberVerb = memberVerbOf(verb, m.draft.runner);\n const oneShot = ONE_SHOT_VERBS.has(memberVerb);\n // A one-shot member (build) needs no other member's outputs: it gets\n // its declared host with only the \"${userData}\"/\"${projectRoot}\"\n // string sugar substituted (tokens stay; its verb reads paths, never\n // outputs; a $map reaches the verb as an empty collection). Everything\n // else resolves against the members started before it and is\n // validated in resolved form.\n const resolved = oneShot\n ? substituteBuiltinEnv(m.draft, resolveEnv.builtins ?? {})\n : resolveHostOutputs(m.draft, {\n outputs,\n ...resolveEnv,\n where: m.file,\n });\n if (wiring.cspRegistrySync && takesCspRegistrySync(m)) {\n resolved.runner = { ...resolved.runner, cspRegistrySync: true };\n }\n const validated = validateHost(\n m.runner,\n m.specifier,\n resolved,\n m.file,\n oneShot ? { tokens: \"allow\" } : {},\n );\n const fn = getVerb(m.runner, m.specifier, memberVerb);\n const where = `${name} (${m.specifier} ${memberVerb})`;\n const argv = memberArgv.get(name) ?? [];\n const handle = toStartedHandle(\n await fn(oneShot ? emptyMaps(validated, resolved) : validated, {\n projectRoot,\n env: ctx.env,\n verb: memberVerb,\n parent: { host: host.name, verb },\n ...(argv.length > 0 ? { argv } : {}),\n }),\n where,\n );\n // Registered before `ready` settles, so a failed start still tears\n // this member down.\n started.push({\n name,\n member: m.member,\n specifier: m.specifier,\n kind: m.runner.kind,\n verb: memberVerb,\n handle,\n outputs: handle.outputs,\n });\n if (handle.ready) await handle.ready;\n // Consumers and the record see the PARSED outputs (schema defaults,\n // transforms, stripped keys), as a standalone run publishes them.\n let memberOutputs = handle.outputs;\n if (!oneShot && isSchemaLike(m.runner.outputsSchema)) {\n const checked = m.runner.outputsSchema.safeParse(handle.outputs);\n if (!checked.success) {\n throw new Error(\n `${where} reported outputs that fail its outputsSchema:\\n${checked.error.issues.map((i) => ` - ${i.path.map(String).join(\".\") || \"<root>\"}: ${i.message}`).join(\"\\n\")}`,\n );\n }\n if (!isPlainObject(checked.data)) {\n throw new Error(\n `${where}: its outputsSchema parsed the outputs to ${JSON.stringify(checked.data)}, not an object.`,\n );\n }\n memberOutputs = checked.data;\n }\n started[started.length - 1].outputs = memberOutputs;\n liveOutputs.set(name, memberOutputs);\n }\n } catch (error) {\n await shutdown();\n throw error;\n }\n\n if (keepsRecord) {\n const recordMembers: Record<string, RunRecordMember> = {};\n for (const m of started) {\n recordMembers[m.name] = {\n host: m.member.host,\n runnerModule: m.specifier,\n kind: m.kind,\n verb: m.verb,\n outputs: m.outputs,\n };\n }\n writeRunRecord(projectRoot, {\n version: 2,\n host: host.name,\n projectName: options.projectName,\n kind: \"compound\",\n verb,\n pid: process.pid,\n startedAt: new Date().toISOString(),\n members: recordMembers,\n ...(options.recordExtra ? { extra: options.recordExtra } : {}),\n });\n }\n\n // The compound owns the exit: members run without process-exiting signal\n // handlers (ctx.parent is set), so one Ctrl-C reaches only this handler.\n const exit = options.exit ?? ((code: number) => process.exit(code));\n let signalled: Promise<void> | undefined;\n const handleSignal = (signal: \"SIGINT\" | \"SIGTERM\") => {\n if (signalled) return signalled;\n const code = signal === \"SIGINT\" ? 130 : 143;\n signalled = shutdown().finally(() => exit(code));\n return signalled;\n };\n if (options.installSignalHandlers !== false) {\n process.on(\"exit\", () => {\n if (keepsRecord) clearRunRecord(projectRoot, host.name);\n });\n process.on(\"SIGINT\", () => void handleSignal(\"SIGINT\"));\n process.on(\"SIGTERM\", () => void handleSignal(\"SIGTERM\"));\n }\n stopFromStream = () => {\n // No supervisor may be left to end a shutdown that hangs.\n const limit = options.stopStreamLimitMs ?? STOP_STREAM_LIMIT_MS;\n setTimeout(() => exit(143), limit).unref();\n void handleSignal(\"SIGTERM\");\n };\n if (stopRequested) stopFromStream();\n\n return { started, shutdown, handleSignal };\n}\n\n/** Load every member's draft and runner, in declaration order. */\nasync function prepareMembers(\n projectRoot: string,\n children: Record<string, ChildWrapper>,\n): Promise<PreparedMember[]> {\n const out: PreparedMember[] = [];\n for (const [key, member] of Object.entries(children)) {\n out.push(await prepareMember(projectRoot, key, member));\n }\n return out;\n}\n\n/** One member's draft and runner. */\nexport async function prepareMember(\n projectRoot: string,\n key: string,\n member: ChildWrapper,\n): Promise<PreparedMember> {\n const draft = await memberDraft(projectRoot, member);\n const specifier = draft.runner.module;\n return {\n key,\n member,\n draft,\n specifier,\n runner: await resolveRunnerModule(projectRoot, specifier),\n file: `hosts/${member.host}/host.js`,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,IAAa,cAAb,cAAiC,MAAM;CACrC,YAAY,SAAiB,MAAe;EAC1C,MAAM,OAAO,GAAG,QAAQ,YAAY,SAAS,OAAO;EACpD,KAAK,OAAO;CACd;AACF;AAIA,MAAa,0BAA0B,EAAE,aAAa;CACpD,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;;CAExB,SAAS,EAAE,QAAQ,CAAC,CAAC,SAAS;;CAE9B,OAAO,EACJ,MAAM,CAAC,EAAE,QAAQ,GAAG,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAC1D,SAAS;;CAEZ,QAAQ,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;AACrD,CAAC;AAED,MAAa,oBAAoB,EAAE,MAAM,CACvC,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,GAChB,uBACF,CAAC;AAcD,SAAgB,qBACd,OACuB;CACvB,IAAI,OAAO,UAAU,UACnB,OAAO;EAAE,QAAQ;EAAO,SAAS;EAAM,OAAO;EAAK,QAAQ,CAAC;CAAE;CAEhE,OAAO;EACL,QAAQ,MAAM;EACd,SAAS,MAAM,WAAW;EAC1B,OAAO,MAAM,SAAS;EACtB,QAAQ,MAAM,UAAU,CAAC;CAC3B;AACF;;;AAIA,SAAgB,uBACd,SACA,OACyB;CACzB,MAAM,aAAa,QAAQ,IAAI,oBAAoB;CACnD,M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