@powerhousedao/host-core 6.4.0-next.0 → 6.4.0-next.2

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compound-Q9sZSEZF.mjs","names":["valueAt","factory","valueAt","isRecord","isRecord","isRecord"],"sources":["../src/drive-schema.ts","../src/connect-composition.ts","../src/plugins.ts","../src/host-schemas.ts","../src/host-ref.ts","../src/plugins-resolve.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/stop-channel.ts","../src/compound-member.ts","../src/spawn-host.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\";\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 (`<slug>-<hash of the path>`) — the\n * same ids classic `ph vetra` produced. `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","/**\n * The config slices Connect's built-in plugins own, and the composition a\n * Connect without a declared one boots from. Browser-safe: `ph run` (dev,\n * serve) and Connect's own runtime work the default out with the same\n * function.\n */\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 function 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. */\nexport function 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 it is written, for a host that\n * declares no `runner.plugins`. `config` is the connect block Connect is\n * 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","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\n// The default Connect composition is worked out in the browser too.\nexport {\n CONNECT_PLUGIN_OWNED_SLICES,\n defaultConnectComposition,\n type ConnectPluginSlices,\n type OwnedConfigSlice,\n} from \"./connect-composition.js\";\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/** An npm package name, as `<package>/<host>` names a package that supplies\n * hosts: `name` or `@scope/name`, each part letters, digits, '-', '.', '_'\n * and '~', not starting with '.' or '_'. Each part is one folder name, the\n * one the package has under node_modules. */\nexport const PACKAGE_NAME_PATTERN =\n /^(?:@[A-Za-z0-9~-][A-Za-z0-9._~-]*\\/)?[A-Za-z0-9~-][A-Za-z0-9._~-]*$/;\n\n/** How a compound names a member's host: its folder under the project's\n * `hosts/` (or, in a package's compound, the package's first), or\n * `<package>/<host>` for one an installed package supplies. */\nexport const HOST_REF_PATTERN = new RegExp(\n `^(?:${PACKAGE_NAME_PATTERN.source.slice(1, -1)}/)?${HOST_NAME_PATTERN.source.slice(1, -1)}$`,\n);\nexport const HOST_REF_MESSAGE =\n \"A member's host is a host folder (`switchboard`), or `<package>/<host>` (`@acme/tools/studio`) for one an installed package supplies.\";\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\n/** A compound member's process: its own, or the compound's (`shared`). */\nexport const memberProcessSchema = z.enum([\"own\", \"shared\"]);\nexport type MemberProcess = z.infer<typeof memberProcessSchema>;\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 // 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).regex(HOST_REF_PATTERN, HOST_REF_MESSAGE),\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 /** Where the member runs: `own`, a child process of the compound\n * (`ph run <host>`), stopped through its stdin; `shared`, in the\n * compound's own process. Default: `own` next to a foreground member\n * (the Cli runner), `shared` otherwise. */\n process: memberProcessSchema.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 existsSync,\n readdirSync,\n readFileSync,\n realpathSync,\n statSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { PACKAGE_NAME_PATTERN } from \"./host-schemas.js\";\n\n/**\n * How a host is addressed (decision D5). A bare name (`switchboard`) is the\n * project's own host, `<project>/hosts/switchboard/`, always: a package\n * cannot shadow it. `<package>/<host>` (`@powerhousedao/vetra-cli/studio`,\n * `tools/studio`) is a host an installed package supplies, in the `hosts/`\n * folder it ships: `<package>/hosts/studio/`. The host is the last segment,\n * so a host name has no `/`. Only inside a package's compound does a bare\n * member name look in that package first (`locateHost`'s `scope`).\n */\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\n/** An installed package that supplies hosts: its name and its real folder,\n * which its host files and their module specifiers resolve from. */\nexport interface HostPackage {\n name: string;\n root: string;\n}\n\nexport interface HostRef {\n /** Absent: the project's own host. */\n package?: string;\n /** The folder under `hosts/`. */\n host: string;\n}\n\n/** Splits a ref at its last `/`; refuses what names no host. */\nexport function parseHostRef(ref: string): HostRef {\n const slash = ref.lastIndexOf(\"/\");\n if (slash === -1) return { host: ref };\n const pkg = ref.slice(0, slash);\n const host = ref.slice(slash + 1);\n if (/^@[^/]*$/.test(pkg) || (ref.startsWith(\"@\") && host === \"\")) {\n throw new HostLoadError(\n `\"${ref}\" names a package, not a host.`,\n `A package's host is <package>/<host>, e.g. \\`ph run ${ref.replace(/\\/$/, \"\")}/<host>\\`.`,\n );\n }\n if (!PACKAGE_NAME_PATTERN.test(pkg)) {\n throw new HostLoadError(\n `\"${ref}\" names no host: a host is <host> (the project's) or <package>/<host>, a host name has no \"/\", and \"${pkg}\" is no package name.`,\n );\n }\n if (host === \"\") {\n throw new HostLoadError(\n `\"${ref}\" names package \"${pkg}\" but no host.`,\n `Write ${pkg}/<host>.`,\n );\n }\n return { package: pkg, host };\n}\n\nexport function formatHostRef(ref: HostRef): string {\n return ref.package === undefined ? ref.host : `${ref.package}/${ref.host}`;\n}\n\n/** Where messages point for a host file: `hosts/<host>/host.js`, behind its\n * package for a package's (`@acme/tools/hosts/studio/host.js`). */\nexport function hostFileLabel(\n folder: string,\n hostPackage?: HostPackage,\n): string {\n const file = `hosts/${folder}/host.js`;\n return hostPackage ? `${hostPackage.name}/${file}` : file;\n}\n\nfunction packageJsonName(dir: string): string | undefined {\n try {\n const name = (\n JSON.parse(readFileSync(path.join(dir, \"package.json\"), \"utf8\")) as {\n name?: unknown;\n }\n ).name;\n return typeof name === \"string\" ? name : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The real folder of the installed package `name`, found from `fromRoot` as\n * Node finds it: the first `<dir>/node_modules/<name>/package.json` on the\n * lookup paths of `<fromRoot>/package.json`, by its real path (a pnpm link\n * leads to the package's own folder, whose dependencies are its own). Not\n * through `exports`, which may not list `package.json`. Undefined when it is\n * not installed there.\n */\nexport function resolvePackageRoot(\n fromRoot: string,\n name: string,\n): string | undefined {\n const root = path.resolve(fromRoot);\n const lookup =\n createRequire(\n pathToFileURL(path.join(root, \"package.json\")).href,\n ).resolve.paths(name) ?? [];\n for (const dir of lookup) {\n const candidate = path.join(dir, name);\n if (existsSync(path.join(candidate, \"package.json\"))) {\n return realpathSync(candidate);\n }\n }\n return undefined;\n}\n\n/** The installed package `name`, found from the project root\n * (resolvePackageRoot). */\nexport function findHostPackage(\n projectRoot: string,\n name: string,\n host: string,\n): HostPackage {\n const root = path.resolve(projectRoot);\n if (packageJsonName(root) === name) {\n throw new HostLoadError(\n `\"${name}/${host}\": \"${name}\" is this project's own package.`,\n `Run the project's own host by its bare name: \\`ph run ${host}\\`.`,\n );\n }\n const found = resolvePackageRoot(root, name);\n if (found !== undefined) return { name, root: found };\n throw new HostLoadError(\n `Package \"${name}\" is not installed in this project, so it supplies no host \"${host}\".`,\n `Add ${name} as a dependency of the project (looked up from ${root}).`,\n );\n}\n\n/** The `<name>/host.js` folders under `<root>/hosts`, sorted; undefined\n * when there is no hosts/ folder. */\nexport function hostFolders(root: string): string[] | undefined {\n const dir = path.join(root, \"hosts\");\n if (!existsSync(dir) || !statSync(dir).isDirectory()) return undefined;\n return readdirSync(dir, { withFileTypes: true })\n .filter(\n (entry) =>\n entry.isDirectory() &&\n existsSync(path.join(dir, entry.name, \"host.js\")),\n )\n .map((entry) => entry.name)\n .sort();\n}\n\n/** Where a host's file is, and who supplies it. */\nexport interface HostLocation {\n /** How it is addressed from anywhere in the project: bare for the\n * project's own, `<package>/<host>` for a package's. A compound starts an\n * own-process member with it, and its record names the member by it. */\n ref: string;\n /** Its folder under `hostsDir`. */\n folder: string;\n /** The `hosts/` folder it is in. */\n hostsDir: string;\n /** The package that supplies it; absent for the project's own. */\n package?: HostPackage;\n}\n\n/** A package's host, or why the package has none by that name. */\nfunction packageHostLocation(pkg: HostPackage, host: string): HostLocation {\n const folders = hostFolders(pkg.root);\n if (folders === undefined || folders.length === 0) {\n throw new HostLoadError(\n `Package \"${pkg.name}\" supplies no hosts: ${pkg.root} has no hosts/<name>/host.js, so \"${pkg.name}/${host}\" cannot run.`,\n );\n }\n if (!folders.includes(host)) {\n throw new HostLoadError(\n `Package \"${pkg.name}\" supplies no host \"${host}\". Its hosts: ${folders.join(\", \")}.`,\n );\n }\n return {\n ref: formatHostRef({ package: pkg.name, host }),\n folder: host,\n hostsDir: path.join(pkg.root, \"hosts\"),\n package: pkg,\n };\n}\n\n/**\n * Where `ref` is. `<package>/<host>` is always the installed package's,\n * found from the project root (also when a package's compound writes it). A\n * bare name is the project's, except in a package's compound (`scope`): there\n * the package's own host of that name comes first. Throws a HostLoadError\n * naming the package and the host. A bare name the project lacks is left to\n * the loader's own message (undefined `package`, project `hostsDir`).\n */\nexport function locateHost(\n projectRoot: string,\n ref: string,\n scope?: HostPackage,\n): HostLocation {\n const parsed = parseHostRef(ref);\n if (parsed.package !== undefined) {\n return packageHostLocation(\n findHostPackage(projectRoot, parsed.package, parsed.host),\n parsed.host,\n );\n }\n const own: HostLocation = {\n ref: parsed.host,\n folder: parsed.host,\n hostsDir: path.join(projectRoot, \"hosts\"),\n };\n if (!scope) return own;\n const supplied = hostFolders(scope.root) ?? [];\n if (supplied.includes(parsed.host)) {\n return packageHostLocation(scope, parsed.host);\n }\n const projects = hostFolders(projectRoot) ?? [];\n if (projects.includes(parsed.host)) return own;\n throw new HostLoadError(\n `Unknown host \"${parsed.host}\": package \"${scope.name}\" supplies none (its hosts: ${supplied.join(\", \") || \"none\"}), and neither does the project (its hosts: ${projects.join(\", \") || \"none\"}).`,\n );\n}\n","import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { z } from \"zod\";\nimport {\n alreadyServed,\n CONNECT_PLUGIN_OWNED_SLICES,\n valueAt,\n} from \"./connect-composition.js\";\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\nexport {\n CONNECT_PLUGIN_OWNED_SLICES,\n defaultConnectComposition,\n type ConnectPluginSlices,\n type OwnedConfigSlice,\n} from \"./connect-composition.js\";\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\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 default composition 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 {\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\". The `reactor.workflows`\n * boolean, removed in 6.4, is reported the same way. clint's `agents.*.host`\n * and 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)) return;\n if (reactor.workflows !== undefined) {\n found.push({\n path: `${base}reactor.workflows`,\n message:\n \"reactor.workflows was removed in 6.4; the workflows plugin under runner.plugins decides: list it to run workflows, leave it out to run none. \" +\n \"On a switchboard, PH_WORKFLOWS_ENABLED=0 still switches them off.\",\n });\n }\n if (!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 * / `\"${package}\"` string sugar, deep-applied to a JSON-shaped value. No node\n * imports, so it ships in `./schema`; the node default for userData is\n * placeholders.ts.\n */\n\nexport interface BuiltinEnv {\n userData?: string;\n projectRoot?: string;\n /** The root of the package that supplies the host (its real folder); the\n * project root for a project host. */\n package?: 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 \"package\",\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}\"`/\n * `\"${package}\"` string 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`/`package`: always resolvable `$env` names and\n * string 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 type { ControlRecord } from \"./control-channel.js\";\nimport type { HostPackage } from \"./host-ref.js\";\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 }`. For\n * a host an installed package supplies, the caller passes the package's\n * folder as the root (`moduleRootOf`).\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 /** The project: the working directory, its `.ph/` state and stores, also\n * for a host a package supplies. */\n projectRoot: string;\n /** Set when an installed package supplies the host\n * (`ph run <package>/<host>`): the module specifiers the host names (its\n * plugins, a Cli's package) resolve from `root`, as its runner did. */\n hostPackage?: HostPackage;\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 /** The host this verb received, read from disk again: loaded, resolved and\n * validated as the first was. For a dev server that follows the project's\n * files; a process keeps the first evaluation of a host file otherwise.\n * Rejects when the files no longer make a valid host. Not set for a\n * compound member. */\n reloadHost?: () => Promise<unknown>;\n /** Set when this runner is a compound's foreground member (its module\n * exports `foreground: true`): it runs in the compound's process, last,\n * and its handle's `exited` ends the stack. */\n foreground?: ForegroundContext;\n}\n\n/** What a compound hands its foreground member. */\nexport interface ForegroundContext {\n /** The other members as the stack sees them now. */\n members(): readonly MemberStatus[];\n /** The stack already runs in another process: nothing of it was started\n * for this run, which reads its outputs from the live record and must\n * end (a command beside the stack). */\n beside: boolean;\n /** The stack as `ph run` addresses it (its run record's key). */\n stack?: string;\n /** Beside a stack that answers on a control channel: where. */\n control?: ControlRecord;\n}\n\n/**\n * One member of a running compound, in the fields a services manager shows\n * for a service instance (`ServiceInstanceStatus` in clint): the service id\n * is the member's name, its endpoints are its URL outputs.\n */\nexport interface MemberStatus {\n /** The member's key in `children`. */\n name: string;\n /** Its host folder. */\n host: string;\n process: \"own\" | \"shared\";\n status: \"starting\" | \"ready\" | \"stopping\" | \"stopped\" | \"failed\";\n /** Its process: a child's, or the compound's for a shared member. */\n pid?: number;\n /** Every URL among its outputs, by dotted path (`drives.lab.url`). */\n endpoints: Record<string, string>;\n /** This run's log file (own-process members). */\n logFile?: string;\n error?: 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 /** The runner owns the terminal (the Cli runner): it reads stdin itself,\n * and in a compound it is the foreground member, whose exit ends the\n * stack (`RunnerContext.foreground`). */\n foreground?: boolean;\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 \"foreground\",\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, or of the package that supplies the host (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 if (\n module.foreground !== undefined &&\n typeof module.foreground !== \"boolean\"\n ) {\n throw new RunnerError(\n `Runner \"${specifier}\" exports a \\`foreground\\` that is not a boolean.`,\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/** Why a one-shot verb (build) does not run on a host an installed package\n * supplies (`ref`, as the project addresses it): the package ships its hosts\n * built, and a build here would write into the installed package (a\n * Connect's outDir) or build the project in its name. The package's own\n * repository builds them, where they are project hosts. */\nexport function packageBuildRefusal(\n ref: string,\n hostPackage: HostPackage,\n verb: string,\n): RunnerIssue {\n return {\n path: \"\",\n message: `${ref} is a host ${hostPackage.name} supplies, and a package's hosts are built by the package: \"${verb}\" does not run on it.`,\n hint: `${hostPackage.name} ships them built; its own repository builds them, where they are project hosts. Build this project's own hosts by their bare names.`,\n };\n}\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, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { Worker } from \"node:worker_threads\";\nimport { z } from \"zod\";\nimport {\n formatHostRef,\n HostLoadError,\n hostFileLabel,\n hostFolders,\n locateHost,\n type HostLocation,\n type HostPackage,\n} from \"./host-ref.js\";\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\nexport { HostLoadError } from \"./host-ref.js\";\n\n/**\n * Loads and pre-validates a `hosts/<name>/host.js` definition: the project's\n * own, or one an installed package supplies (`<package>/<host>`, host-ref.ts).\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 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\": it defines\n * no host, so nothing runs from it, as from an absent one\n * ({@link withoutHostsMessage}). */\nexport function probeHostsFolder(projectRoot: string): HostsFolderStatus {\n const dir = path.join(projectRoot, \"hosts\");\n const hosts = hostFolders(projectRoot);\n if (hosts === undefined) return { kind: \"absent\" };\n return hosts.length === 0\n ? { kind: \"empty\", dir }\n : { kind: \"present\", dir, hosts };\n}\n\n/**\n * Why `subject` cannot run in a project whose hosts/ folder is absent or\n * empty, and what adds the host files. One wording, for `ph run <host>` and\n * for the `ph dev`, `ph connect` and `ph switchboard` sugar.\n */\nexport function withoutHostsMessage(\n probe: Exclude<HostsFolderStatus, { kind: \"present\" }>,\n subject: string,\n): string {\n const found =\n probe.kind === \"empty\"\n ? `hosts/ exists at ${probe.dir} but contains no <name>/host.js`\n : \"This project has no hosts/ folder\";\n return `${found}, so ${subject} cannot run. Run \\`ph migrate\\` to add the host files.`;\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 /** Its folder under `hosts/`. */\n name: string;\n dir: string;\n file: string;\n host: HostDefinition;\n /** How it is addressed from anywhere in the project: its folder for the\n * project's own host, `<package>/<host>` for a package's. */\n ref?: string;\n /** The package that supplies it; absent for the project's own. Its\n * runner and plugin specifiers resolve from `package.root`. */\n package?: HostPackage;\n}\n\nexport interface LoadHostOptions {\n /** The package whose compound names this host: a bare name looks in its\n * `hosts/` first, then in the project's. */\n scope?: HostPackage;\n}\n\n/** Where a loaded host's module specifiers resolve from: its package's\n * folder, else the project root. */\nexport function moduleRootOf(\n projectRoot: string,\n loaded: Pick<LoadedHost, \"package\">,\n): string {\n return loaded.package?.root ?? projectRoot;\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\n/** `hostName` is a ref: the project's folder name, or `<package>/<host>`. */\nexport async function loadHost(\n projectRoot: string,\n hostName: string,\n options: LoadHostOptions = {},\n): Promise<LoadedHost> {\n return importHost(projectRoot, hostName, true, false, options.scope);\n}\n\n/**\n * `loadHost`, evaluated again: the host file and what it imports are read as\n * they are on disk now. A process keeps the first evaluation of a module, so\n * `loadHost` returns the host as it was when the process first loaded it; a\n * dev server that follows powerhouse.config.json asks for this one.\n */\nexport async function loadHostFresh(\n projectRoot: string,\n hostName: string,\n options: LoadHostOptions = {},\n): Promise<LoadedHost> {\n return importHost(projectRoot, hostName, true, true, options.scope);\n}\n\nconst FRESH_IMPORT_WORKER = `\nconst { parentPort, workerData } = require(\"node:worker_threads\");\nimport(workerData.url).then(\n (module) => {\n try {\n parentPort.postMessage({ host: module.default });\n } catch (error) {\n parentPort.postMessage({ error: String(error) });\n }\n },\n (error) => parentPort.postMessage({ error: String(error) }),\n);\n`;\n\n/** The default export of a module, evaluated in a worker: a worker has its\n * own module graph, so the file and its imports are read again. Host files\n * export data, which is what reaches this thread. */\nfunction importDefaultFresh(url: string, file: string): Promise<unknown> {\n return new Promise((resolve, reject) => {\n const worker = new Worker(FRESH_IMPORT_WORKER, {\n eval: true,\n workerData: { url },\n });\n const fail = (reason: string) =>\n reject(new HostLoadError(`${file} could not be read again: ${reason}`));\n worker.once(\"message\", (message: { host?: unknown; error?: string }) => {\n if (message.error !== undefined) fail(message.error);\n else resolve(message.host);\n void worker.terminate();\n });\n worker.once(\"error\", (error) => fail(String(error)));\n worker.once(\"exit\", () => fail(\"its worker exited without an answer\"));\n });\n}\n\n/** Where `ref` is; for the project's own host, the loader's messages when\n * its hosts/ folder lacks it. */\nfunction locateLoadable(\n projectRoot: string,\n ref: string,\n scope?: HostPackage,\n): HostLocation {\n const location = locateHost(projectRoot, ref, scope);\n if (location.package) return location;\n const probe = probeHostsFolder(projectRoot);\n if (probe.kind !== \"present\") {\n throw new HostLoadError(withoutHostsMessage(probe, `the host \"${ref}\"`));\n }\n if (!probe.hosts.includes(location.folder)) {\n throw new HostLoadError(\n `Unknown host \"${ref}\". Available hosts: ${probe.hosts.join(\", \")}.`,\n );\n }\n return location;\n}\n\nasync function importHost(\n projectRoot: string,\n hostName: string,\n checkOutputs: boolean,\n fresh = false,\n scope?: HostPackage,\n): Promise<LoadedHost> {\n const location = locateLoadable(projectRoot, hostName, scope);\n const { folder, hostsDir } = location;\n\n const file = path.join(hostsDir, folder, HOST_FILE);\n const producers = lintHostImportGraph(hostsDir, folder);\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, location, producer);\n }\n }\n\n const url = pathToFileURL(file).href;\n const host = fresh\n ? await importDefaultFresh(url, file)\n : ((await import(url)) as { default?: unknown }).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: folder,\n dir: path.dirname(file),\n file,\n host: host as HostDefinition,\n ref: location.ref,\n ...(location.package ? { package: location.package } : {}),\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 loaded = await importHost(projectRoot, hostName, false);\n const { host, file } = loaded;\n const moduleRoot = moduleRootOf(projectRoot, loaded);\n const runnerModule = host.runner.module;\n const runner = await resolveRunnerModule(moduleRoot, 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 moduleRoot,\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 // The folder: what the tokens in its own package's files name it by.\n const folder = loaded.name;\n return {\n host: folder,\n runnerModule,\n outputsSchema,\n drives: sortedDrives,\n hash: computeOutputsHash({\n host: folder,\n runnerModule,\n outputsSchema,\n drives: sortedDrives,\n }),\n };\n}\n\nasync function assertOutputsFileFresh(\n projectRoot: string,\n consumer: HostLocation,\n producer: string,\n): Promise<void> {\n const { hostsDir } = consumer;\n const where = consumer.package ? `${consumer.package.name}/` : \"\";\n const rel = `${where}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 `${where}hosts/${consumer.folder} imports ${rel}, but there is no ${hostFileLabel(producer, consumer.package)} to produce it.`,\n \"Delete the orphaned outputs.js and fix the import.\",\n );\n }\n // A sibling in the same hosts/ folder: the package's own, for a package's.\n const description = await describeHostOutputs(\n projectRoot,\n formatHostRef({ package: consumer.package?.name, host: producer }),\n );\n if (!description) {\n throw new HostLoadError(\n `${where}hosts/${consumer.folder} imports ${rel}, but ${where}hosts/${producer}'s runner declares no outputsSchema, so it produces no outputs.`,\n );\n }\n if (actual !== description.hash) {\n throw new HostLoadError(\n consumer.package\n ? `${rel} is stale against the runner this project resolves for it (its outputsSchema or declared drives differ from those it was generated from): package \"${consumer.package.name}\" was built against another version of \"${description.runnerModule}\".`\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 /** Every argument goes to the runner as typed, unchecked: a runner whose\n * host parses its own (the Cli runner hands them to the Cli). */\n passthrough?: boolean;\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 (schema.passthrough === undefined ||\n typeof schema.passthrough === \"boolean\")\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. A `passthrough` runner gets\n * them all, in order.\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 if (schema.passthrough) return [...argv];\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 *\n * With a `foreground` member (the one that owns the terminal) the members\n * take only their member-named options, at the front; the first other\n * argument, or a literal `--`, starts the foreground member's own, checked\n * against its runner's schema (a passthrough runner takes them as typed).\n */\nexport function splitCompoundArgv(\n argv: readonly string[],\n host: string,\n members: readonly CompoundArgvMember[],\n foreground?: string,\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 const owner = members.find((m) => m.key === foreground);\n if (owner) {\n let i = 0;\n for (; i < argv.length; i++) {\n const token = argv[i];\n if (token === \"--\") {\n i++;\n break;\n }\n const equals = token.startsWith(\"-\") ? token.indexOf(\"=\") : -1;\n const name = equals === -1 ? token : token.slice(0, equals);\n const named = schemas.filter(\n ({ key, schema }) =>\n key !== owner.key && schema.memberOptions?.[name] !== undefined,\n );\n if (named.length === 0) break;\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 const { key, schema } = named[0];\n const option = schema.memberOptions?.[name] ?? name;\n if (equals !== -1) {\n // `--switchboard-port=4001` keeps its `=4001`\n perMember.get(key)?.push(option + token.slice(name.length));\n } else if (i + 1 >= argv.length) {\n throw new RunnerError(`${where}: ${name} needs a value.`);\n } else {\n perMember.get(key)?.push(option, argv[i + 1]);\n i++;\n }\n }\n perMember.set(\n owner.key,\n checkRunnerArgv(argv.slice(i), {\n host,\n runner: owner.runner,\n schema: owner.schema,\n }),\n );\n return perMember;\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 {\n hostNameSchema,\n PACKAGE_NAME_PATTERN,\n runnerKindSchema,\n} 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. A host an installed package\n * supplies has its record in a folder named after the package,\n * `.ph/run/<package>/<host>.json`, and says which in `package`.\n */\n\nconst outputsSchema = z.record(z.string(), z.unknown());\n\nexport const runRecordMemberSchema = z.strictObject({\n /** The member's host as the project addresses it: its folder, or\n * `<package>/<host>` for one a package supplies. */\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 /** The installed package that supplies the host; absent for the\n * project's own. */\n package: z.string().regex(PACKAGE_NAME_PATTERN).optional(),\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 {\n HOST_NAME_MESSAGE,\n hostNameSchema,\n PACKAGE_NAME_PATTERN,\n} 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 * A host an installed package supplies is keyed `<package>/<name>`\n * ({@link runRecordKey}) and filed in a folder named after the package,\n * `.ph/run/@scope/pkg/<name>.json`, so it never meets a project host of the\n * same name. The functions below take either key.\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/** The key a host's record is filed under: its `name`, behind the package\n * that supplies it when it is not the project's own (`@acme/tools/studio`),\n * as `ph run` addresses the host. */\nexport function runRecordKey(name: string, hostPackage?: string): string {\n return hostPackage === undefined ? name : `${hostPackage}/${name}`;\n}\n\n/** The key of a record as read: where it is filed. */\nexport function recordKeyOf(record: Pick<RunRecord, \"host\" | \"package\">) {\n return runRecordKey(record.host, record.package);\n}\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, key: string, env?: Env): string {\n const dir = runDir(projectDir, env);\n const slash = key.lastIndexOf(\"/\");\n const hostName = key.slice(slash + 1);\n const pkg = slash === -1 ? undefined : key.slice(0, slash);\n const folder =\n pkg === undefined\n ? path.resolve(dir)\n : path.resolve(dir, ...pkg.split(\"/\"));\n const file = path.resolve(folder, `${hostName}.json`);\n if (\n !hostNameSchema.safeParse(hostName).success ||\n (pkg !== undefined && !PACKAGE_NAME_PATTERN.test(pkg)) ||\n path.dirname(file) !== folder\n ) {\n throw new Error(`\"${key}\" can't name a run record. ${HOST_NAME_MESSAGE}`);\n }\n return file;\n}\n\n/** The record keys under `.ph/run/`: `<name>.json` files, and those in a\n * package's folder (`<pkg>/` or `@scope/<pkg>/`). */\nfunction recordKeys(dir: string): string[] {\n const entries = (at: string) => {\n try {\n return fs.readdirSync(at, { withFileTypes: true });\n } catch {\n return [];\n }\n };\n const records = (at: string, prefix: string) =>\n entries(at)\n .filter((entry) => entry.isFile() && entry.name.endsWith(\".json\"))\n .map((entry) => `${prefix}${entry.name.slice(0, -\".json\".length)}`);\n const keys = records(dir, \"\");\n for (const entry of entries(dir)) {\n if (!entry.isDirectory()) continue;\n const at = path.join(dir, entry.name);\n if (!entry.name.startsWith(\"@\")) {\n keys.push(...records(at, `${entry.name}/`));\n continue;\n }\n for (const inner of entries(at)) {\n if (!inner.isDirectory()) continue;\n keys.push(\n ...records(path.join(at, inner.name), `${entry.name}/${inner.name}/`),\n );\n }\n }\n return keys;\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/`, package hosts' included (invalid\n * and v1 files skipped). */\nexport function listRunRecords(\n projectDir: string,\n env: Env = process.env,\n): RunRecord[] {\n return recordKeys(runDir(projectDir, env)).flatMap((key) => {\n const record = readRunRecord(projectDir, key, env);\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, recordKeyOf(record));\n const valid = runRecordSchema.parse(record);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n const text = `${JSON.stringify(valid, null, 2)}\\n`;\n if (valid.extra?.control === undefined) {\n fs.writeFileSync(target, text);\n return;\n }\n // It holds the control channel's token: the user's alone where the file\n // mode says so (on Windows the folder's access rules decide).\n fs.rmSync(target, { force: true });\n fs.writeFileSync(target, text, { mode: 0o600 });\n if (process.platform !== \"win32\") fs.chmodSync(target, 0o600);\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 net from \"node:net\";\nimport {\n clearRunRecord,\n isPidAlive,\n probeRun,\n readProjectName,\n readRunRecord,\n} from \"./run-record.js\";\n\n/** Set by a supervisor that holds this process's stdin. */\nexport const STOP_ON_STDIN_ENV = \"PH_STOP_ON_STDIN\";\n\n/**\n * Windows has no SIGTERM: `process.kill(pid, \"SIGTERM\")` ends the process at\n * once, so no handler runs and a stack's stores are left as a crash leaves\n * them. A started host therefore listens on a pipe named after its pid, and\n * a connection to it is delivered as the SIGTERM it stands for. Elsewhere\n * the signal itself does this, and there is no channel.\n */\nexport function stopChannelPath(\n pid: number,\n platform: NodeJS.Platform = process.platform,\n): string | undefined {\n return platform === \"win32\" ? `\\\\\\\\.\\\\pipe\\\\ph-stop-${pid}` : undefined;\n}\n\n/** Calls `onStop` for each connection to `channel`. The server holds no\n * process open, and one that cannot listen leaves the host running without\n * a channel rather than not running. */\nexport function listenForStop(channel: string, onStop: () => void): net.Server {\n const server = net.createServer((socket) => {\n socket.on(\"error\", () => undefined);\n // The asker waits for this end: the request arrived.\n socket.end();\n onStop();\n });\n server.on(\"error\", () => undefined);\n server.listen(channel);\n server.unref();\n return server;\n}\n\nlet installed = false;\n\n/** What a host's process calls once before it starts anything: from then on\n * {@link requestStop} reaches its SIGTERM handlers on every platform. */\nexport function installStopChannel(): void {\n const channel = stopChannelPath(process.pid);\n if (!channel || installed) return;\n installed = true;\n listenForStop(channel, () => {\n // As the signal: the handlers when there are any, the exit when not.\n if (!process.emit(\"SIGTERM\", \"SIGTERM\")) process.exit(143);\n });\n}\n\nconst ASK_TIMEOUT_MS = 2_000;\n\n/** Connects to a stop channel; true once the listener took the request. */\nexport function askToStop(\n channel: string,\n timeoutMs: number = ASK_TIMEOUT_MS,\n): Promise<boolean> {\n return new Promise((resolve) => {\n let connected = false;\n const socket = net.connect(channel);\n socket.setTimeout(timeoutMs, () => socket.destroy());\n socket.once(\"connect\", () => (connected = true));\n socket.on(\"error\", () => undefined);\n socket.once(\"close\", () => resolve(connected));\n socket.resume();\n });\n}\n\n/**\n * Asks the process to stop as SIGTERM would. False when it could not be\n * asked: on Windows a process without a stop channel (started by an older\n * version, or not a host), which only a kill ends.\n */\nexport async function requestStop(\n pid: number,\n platform: NodeJS.Platform = process.platform,\n): Promise<boolean> {\n const channel = stopChannelPath(pid, platform);\n if (channel) return askToStop(channel);\n try {\n process.kill(pid, \"SIGTERM\");\n } catch {\n // Already gone.\n }\n return true;\n}\n\nexport type StopRunResult =\n /** No live instance of this host for this project. */\n | { status: \"none\" }\n | { status: \"foreign\"; pid: number; projectName: string }\n | { status: \"stopped\"; pid: number }\n /** It runs, and has no stop channel. */\n | { status: \"unreachable\"; pid: number }\n /** Asked, and still running after `timeoutMs`. */\n | { status: \"timeout\"; pid: number };\n\nexport interface StopRunOptions {\n /** How long the host may take to stop (default {@link STOP_RUN_TIMEOUT_MS}). */\n timeoutMs?: number;\n env?: Readonly<Record<string, string | undefined>>;\n}\n\nexport const STOP_RUN_TIMEOUT_MS = 60_000;\n\n/** Asks the project's running `hostName` to stop and waits until its process\n * is gone. It never kills: a host that does not answer keeps running. */\nexport async function stopRun(\n projectDir: string,\n hostName: string,\n options: StopRunOptions = {},\n): Promise<StopRunResult> {\n const env = options.env ?? process.env;\n const projectName = readProjectName(projectDir);\n const probe = probeRun(projectDir, hostName, projectName, env);\n if (probe.status === \"none\" || probe.status === \"stale\") {\n return { status: \"none\" };\n }\n const { pid } = probe.record;\n if (probe.status === \"foreign\") {\n return { status: \"foreign\", pid, projectName: probe.record.projectName };\n }\n if (!(await requestStop(pid))) return { status: \"unreachable\", pid };\n const deadline = Date.now() + (options.timeoutMs ?? STOP_RUN_TIMEOUT_MS);\n while (isPidAlive(pid)) {\n if (Date.now() >= deadline) return { status: \"timeout\", pid };\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n // A host clears its own record as it exits; one that was killed did not.\n if (readRunRecord(projectDir, hostName, env)?.pid === pid) {\n clearRunRecord(projectDir, hostName, env);\n }\n return { status: \"stopped\", pid };\n}\n","/**\n * How a compound hands an own-process member its host. The member's\n * `host.js` alone is not the member: the compound's wrapper (reactor, config\n * and runner overrides) and its resolved tokens are. So the compound\n * resolves the member as it would in its own process and the child's\n * `ph run <folder>` runs that host instead of reading the file.\n */\n\nimport { formatPath } from \"./resolve/walk.js\";\nimport { RunnerError } from \"./runner-resolver.js\";\n\n/** Carries a {@link CompoundMemberHost} as JSON to the child's `ph run`. */\nexport const COMPOUND_MEMBER_ENV = \"PH_COMPOUND_MEMBER\";\n\n/** The most an environment variable holds on Windows, in characters; counted\n * here with its name and `=`, and kept on every platform, so a stack that\n * starts on one starts on all. */\nexport const ENV_VALUE_LIMIT = 32_767;\n\nexport interface CompoundMemberHost {\n /** The compound host's name. */\n compound: string;\n /** The member's key in the compound's `children`. */\n member: string;\n /** The member's host folder: the child's `ph run <folder>`. */\n folder: string;\n /** The member's host, its wrapper applied and its tokens resolved. */\n host: Record<string, unknown>;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** A value JSON would not give back as it is, and where. */\nexport interface JsonChange {\n path: (string | number)[];\n /** What it is, and what JSON makes of it. */\n what: string;\n}\n\n/**\n * The first value in `value` that a JSON round trip drops or changes: a\n * function, symbol or bigint, `undefined` or an empty slot in an array, a\n * number that is not finite, an instance of a class (a Date, a Map, …) or\n * any object with `toJSON`, a symbol key, a cycle. An object property that\n * is `undefined` is fine: JSON drops it, and an absent key reads the same.\n */\nexport function jsonChange(value: unknown): JsonChange | undefined {\n const ancestors = new Set<object>();\n const walk = (\n item: unknown,\n path: (string | number)[],\n ): JsonChange | undefined => {\n switch (typeof item) {\n case \"string\":\n case \"boolean\":\n return undefined;\n case \"number\":\n return Number.isFinite(item)\n ? undefined\n : { path, what: `the number ${item}, which JSON writes as null` };\n case \"undefined\":\n return { path, what: \"undefined, which JSON writes as null here\" };\n case \"function\":\n return { path, what: \"a function, which JSON drops\" };\n case \"symbol\":\n return { path, what: \"a symbol, which JSON drops\" };\n case \"bigint\":\n return { path, what: \"a bigint, which JSON cannot write\" };\n }\n if (item === null) return undefined;\n const object = item as object;\n if (ancestors.has(object)) {\n return { path, what: \"a cycle, which JSON cannot write\" };\n }\n const prototype: unknown = Object.getPrototypeOf(object);\n if (Array.isArray(object) && prototype === Array.prototype) {\n ancestors.add(object);\n try {\n for (let i = 0; i < object.length; i++) {\n if (!(i in object)) {\n return {\n path: [...path, i],\n what: \"an empty slot, which JSON writes as null\",\n };\n }\n const found = walk(object[i], [...path, i]);\n if (found) return found;\n }\n return undefined;\n } finally {\n ancestors.delete(object);\n }\n }\n if (object instanceof Date) {\n return { path, what: \"a Date, which JSON writes as a string\" };\n }\n if (prototype !== Object.prototype && prototype !== null) {\n const name = (object as { constructor?: { name?: unknown } }).constructor\n ?.name;\n return {\n path,\n what: `${typeof name === \"string\" && name ? `a ${name}` : \"an instance of a class\"}, which JSON writes as a plain object`,\n };\n }\n if (typeof (object as { toJSON?: unknown }).toJSON === \"function\") {\n return { path, what: \"an object with toJSON, which JSON replaces\" };\n }\n if (Object.getOwnPropertySymbols(object).length > 0) {\n return { path, what: \"a symbol-keyed property, which JSON drops\" };\n }\n ancestors.add(object);\n try {\n for (const [key, entry] of Object.entries(object)) {\n if (entry === undefined) continue;\n const found = walk(entry, [...path, key]);\n if (found) return found;\n }\n return undefined;\n } finally {\n ancestors.delete(object);\n }\n };\n return walk(value, []);\n}\n\n/**\n * The member's host as the JSON its child reads from COMPOUND_MEMBER_ENV.\n * Refuses one JSON would change, or too long for an environment variable,\n * naming the member, the value and the way out: the member runs in the\n * compound's process, where nothing is copied.\n */\nexport function encodeCompoundMember(member: CompoundMemberHost): string {\n const where = `hosts/${member.compound}: member \"${member.member}\" cannot run in its own process`;\n const hint = `Run it in the compound's process: children.${member.member}.process: \"shared\".`;\n const change = jsonChange(member.host);\n if (change) {\n throw new RunnerError(\n `${where}: its host holds ${change.what}, at ${formatPath(change.path)}; the child gets its host as JSON.`,\n hint,\n );\n }\n const json = JSON.stringify(member);\n const size = COMPOUND_MEMBER_ENV.length + 1 + json.length;\n if (size > ENV_VALUE_LIMIT) {\n throw new RunnerError(\n `${where}: its host is ${json.length} characters as JSON, and the child gets it in an environment variable, which holds at most ${ENV_VALUE_LIMIT} on Windows.`,\n hint,\n );\n }\n return json;\n}\n\n/**\n * The member host a compound handed this process for `folder`, taken out of\n * `env` so nothing this process starts inherits it. Undefined when there is\n * none; throws when it is malformed or names another folder.\n */\nexport function takeCompoundMember(\n env: Record<string, string | undefined>,\n folder: string,\n): CompoundMemberHost | undefined {\n const raw = env[COMPOUND_MEMBER_ENV];\n if (raw === undefined) return undefined;\n delete env[COMPOUND_MEMBER_ENV];\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n parsed = undefined;\n }\n if (\n !isRecord(parsed) ||\n typeof parsed.compound !== \"string\" ||\n typeof parsed.member !== \"string\" ||\n typeof parsed.folder !== \"string\" ||\n !isRecord(parsed.host)\n ) {\n throw new Error(\n `${COMPOUND_MEMBER_ENV} does not hold a compound member's host.`,\n );\n }\n if (parsed.folder !== folder) {\n throw new Error(\n `${COMPOUND_MEMBER_ENV} holds member \"${parsed.member}\" (hosts/${parsed.folder}) of compound \"${parsed.compound}\", not hosts/${folder}.`,\n );\n }\n return parsed as unknown as CompoundMemberHost;\n}\n","import { spawn, type ChildProcess } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n COMPOUND_MEMBER_ENV,\n encodeCompoundMember,\n type CompoundMemberHost,\n} from \"./compound-member.js\";\nimport { loadHost } from \"./host-loader.js\";\nimport { locateHost } from \"./host-ref.js\";\nimport { killTree } from \"./kill-tree.js\";\nimport { clearRunRecord, listRunRecords, recordKeyOf } from \"./run-record.js\";\nimport type { RunRecord } from \"./run-record-schema.js\";\nimport {\n isSchemaLike,\n ONE_SHOT_VERBS,\n resolveRunnerModule,\n STORE_VERBS,\n} from \"./runner-resolver.js\";\nimport { STOP_ON_STDIN_ENV } from \"./stop-channel.js\";\n\nexport interface SpawnHostOptions {\n projectRoot: string;\n /** Folder name under hosts/, or `<package>/<host>` for a host an\n * installed package supplies: what the child's `ph run` takes. */\n host: string;\n /** The child's PH_USER_DATA_DIR (created if missing). */\n dataDir: string;\n verb?: string;\n /** What follows `ph run <host> [verb]`: the runner's arguments. */\n argv?: readonly string[];\n /** Merged over the base env; may not set PH_USER_DATA_DIR. */\n env?: Record<string, string>;\n /** The env the child starts from instead of the clean one, as it is: a\n * compound hands its members its own, so a member sees what it would in\n * the compound's process. */\n baseEnv?: Readonly<Record<string, string | undefined>>;\n /** The host the child runs instead of reading `hosts/<host>/host.js`: a\n * compound's member, its wrapper applied and its tokens resolved. */\n definition?: Omit<CompoundMemberHost, \"folder\">;\n /** Ask the child to stop through its stdin (it gets a pipe and\n * PH_STOP_ON_STDIN=1): a request on every platform, which this process\n * ending makes too; after stopTimeoutMs its whole process tree is killed.\n * Without it a stop is SIGTERM, on Windows the kill itself, and SIGKILL of\n * the child follows after stopTimeoutMs. */\n stopOnStdin?: boolean;\n /** ph-cli entry; default: the project's `@powerhousedao/ph-cli/dist/cli.mjs`. */\n cli?: string;\n readyTimeoutMs?: number;\n stopTimeoutMs?: number;\n /** Before ready: stop and reject. After: stop. */\n signal?: AbortSignal;\n onOutput?: (stream: \"stdout\" | \"stderr\", chunk: string) => void;\n /** Appends both streams. */\n logFile?: string;\n}\n\nexport interface HostExit {\n code: number | null;\n signal: NodeJS.Signals | null;\n /** SIGKILL after stopTimeoutMs. */\n forced: boolean;\n}\n\nexport interface SpawnedHost {\n pid: number;\n dataDir: string;\n record: RunRecord;\n outputs: Record<string, unknown> | undefined;\n members: RunRecord[\"members\"];\n /** Resolves (never rejects) when the child exits. */\n exited: Promise<HostExit>;\n /** SIGTERM (or the end of its stdin), SIGKILL after stopTimeoutMs, clear\n * a leftover record. */\n stop(): Promise<HostExit>;\n}\n\nexport type SpawnHostPhase = \"exited\" | \"timeout\" | \"aborted\";\n\n/** The tail line before which a timed-out or aborted run's output is its own. */\nexport const SPAWN_STOPPING_NOTE = \"spawnHost: stopping it\";\n\nexport class SpawnHostError extends Error {\n constructor(\n message: string,\n readonly phase: SpawnHostPhase,\n readonly outputTail: string,\n readonly exit?: HostExit,\n ) {\n super(\n outputTail ? `${message}\\n--- output tail ---\\n${outputTail}` : message,\n );\n this.name = \"SpawnHostError\";\n }\n}\n\nconst READY_TIMEOUT_MS = 120_000;\nconst STOP_TIMEOUT_MS = 30_000;\nconst POLL_MS = 100;\nconst TAIL_BYTES = 8 * 1024;\n// A grandchild may hold the pipes open past the child's exit.\nconst CLOSE_WAIT_MS = 1_000;\n\nconst BASE_ENV_KEYS = [\"PATH\", \"HOME\", \"TMPDIR\"];\nconst WIN32_ENV_KEYS = [\n \"SystemRoot\",\n \"USERPROFILE\",\n \"APPDATA\",\n \"LOCALAPPDATA\",\n \"TEMP\",\n \"TMP\",\n \"ComSpec\",\n \"PATHEXT\",\n];\n\n/** The child's whole env: without a `baseEnv`, no other `process.env` key\n * reaches it. */\nfunction childEnv(\n dataDir: string,\n env: Record<string, string> = {},\n baseEnv?: Readonly<Record<string, string | undefined>>,\n): Record<string, string> {\n if (\"PH_USER_DATA_DIR\" in env) {\n throw new Error(\n \"spawnHost: set the data dir with `dataDir`, not env.PH_USER_DATA_DIR.\",\n );\n }\n if (baseEnv) {\n const base: Record<string, string> = {};\n for (const [key, value] of Object.entries(baseEnv)) {\n if (value !== undefined) base[key] = value;\n }\n return { ...base, PH_USER_DATA_DIR: dataDir, ...env };\n }\n const keys =\n process.platform === \"win32\"\n ? [...BASE_ENV_KEYS, ...WIN32_ENV_KEYS]\n : BASE_ENV_KEYS;\n const base: Record<string, string> = {};\n for (const key of keys) {\n const value = process.env[key];\n if (value !== undefined) base[key] = value;\n }\n return {\n ...base,\n PH_USER_DATA_DIR: dataDir,\n PH_NO_TELEMETRY: \"1\",\n PH_NO_DOTENV: \"1\",\n ...env,\n };\n}\n\n/** The project's ph-cli, else its ph-run (a packaged app has only that). */\nfunction resolvePhCliEntry(projectRoot: string): string {\n const require_ = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n let pkgPath: string;\n try {\n pkgPath = require_.resolve(\"@powerhousedao/ph-cli/package.json\");\n } catch (error) {\n try {\n pkgPath = require_.resolve(\"@powerhousedao/ph-run/package.json\");\n } catch {\n throw error;\n }\n }\n return path.join(path.dirname(pkgPath), \"dist\", \"cli.mjs\");\n}\n\n/** Readiness waits for a record; refuse a host/verb that writes none. */\nasync function assertWritesRecord(\n projectRoot: string,\n host: string,\n verb: string | undefined,\n definition: Record<string, unknown> | undefined,\n): Promise<void> {\n if (\n verb !== undefined &&\n (ONE_SHOT_VERBS.has(verb) || STORE_VERBS.has(verb))\n ) {\n throw new Error(\n `spawnHost: \"${verb}\" is a one-shot verb; it writes no run record to wait for.`,\n );\n }\n const declared = (definition ?? (await loadHost(projectRoot, host)).host) as {\n runner: { module: string };\n config?: { runtimeRecord?: unknown };\n };\n const specifier = declared.runner.module;\n // As the child resolves it: from the package that supplies the host.\n const supplier = locateHost(projectRoot, host).package;\n const runner = await resolveRunnerModule(\n supplier?.root ?? projectRoot,\n specifier,\n );\n if (runner.kind === \"compound\") {\n const config = declared.config;\n if (config?.runtimeRecord === false) {\n throw new Error(\n `spawnHost: hosts/${host} sets config.runtimeRecord: false, so it writes no run record to wait for.`,\n );\n }\n return;\n }\n if (!isSchemaLike(runner.outputsSchema)) {\n throw new Error(\n `spawnHost: hosts/${host} runs \"${specifier}\", which exports no outputsSchema, so it writes no run record to wait for.`,\n );\n }\n}\n\nconst sleep = (ms: number) =>\n new Promise<void>((resolve) => {\n setTimeout(resolve, ms).unref();\n });\n\n// Children still running when this process exits get SIGTERM, so a launcher\n// that exits without stop() leaves no host behind. One stopped through its\n// stdin is not tracked: this process ending closes that pipe, which asks it\n// to stop, where SIGTERM would be the kill on Windows.\nconst live = new Set<ChildProcess>();\nlet exitHookInstalled = false;\nfunction track(child: ChildProcess): void {\n live.add(child);\n child.once(\"exit\", () => live.delete(child));\n if (exitHookInstalled) return;\n exitHookInstalled = true;\n process.once(\"exit\", () => {\n for (const running of live) running.kill(\"SIGTERM\");\n });\n}\n\n/**\n * `ph run <host> [verb]` as a child; ready when its run record appears.\n *\n * The child shares this process's group, so a terminal Ctrl-C reaches both.\n * It runs the project's own ph-cli (else its ph-run): one older than\n * PH_NO_DOTENV reads the project's `.env` anyway.\n */\nexport async function spawnHost(\n options: SpawnHostOptions,\n): Promise<SpawnedHost> {\n const projectRoot = path.resolve(options.projectRoot);\n const dataDir = path.resolve(options.dataDir);\n // Before anything else: a host that does not survive JSON, or does not fit\n // an environment variable, fails here, not as a child that runs another.\n const member = options.definition\n ? encodeCompoundMember({ ...options.definition, folder: options.host })\n : undefined;\n const env = childEnv(\n dataDir,\n {\n ...options.env,\n ...(options.stopOnStdin ? { [STOP_ON_STDIN_ENV]: \"1\" } : {}),\n ...(member === undefined ? {} : { [COMPOUND_MEMBER_ENV]: member }),\n },\n options.baseEnv,\n );\n const readerEnv = { PH_USER_DATA_DIR: dataDir };\n const readyTimeoutMs = options.readyTimeoutMs ?? READY_TIMEOUT_MS;\n const stopTimeoutMs = options.stopTimeoutMs ?? STOP_TIMEOUT_MS;\n const { signal, stopOnStdin = false } = options;\n\n if (signal?.aborted) {\n throw new SpawnHostError(\"spawnHost: aborted before start.\", \"aborted\", \"\");\n }\n await assertWritesRecord(\n projectRoot,\n options.host,\n options.verb,\n options.definition?.host,\n );\n const cli = options.cli ?? resolvePhCliEntry(projectRoot);\n fs.mkdirSync(dataDir, { recursive: true });\n\n const log = options.logFile\n ? fs.createWriteStream(options.logFile, { flags: \"a\" })\n : undefined;\n let tail = \"\";\n log?.on(\"error\", (error) => {\n tail = (tail + `logFile: ${error.message}\\n`).slice(-TAIL_BYTES);\n });\n const args = [cli, \"run\", options.host];\n if (options.verb !== undefined) args.push(options.verb);\n if (options.argv && options.argv.length > 0) {\n args.push(\"--\", ...options.argv);\n }\n const child = spawn(process.execPath, args, {\n cwd: projectRoot,\n env,\n stdio: [stopOnStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n // A child that is gone takes its end of the pipe with it.\n child.stdin?.on(\"error\", () => undefined);\n if (!stopOnStdin) track(child);\n const { stdout, stderr } = child;\n if (!stdout || !stderr) throw new Error(\"spawnHost: the child has no pipes.\");\n\n const onChunk = (stream: \"stdout\" | \"stderr\") => (chunk: string) => {\n tail = (tail + chunk).slice(-TAIL_BYTES);\n log?.write(chunk);\n try {\n options.onOutput?.(stream, chunk);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n tail = (tail + `onOutput: ${message}\\n`).slice(-TAIL_BYTES);\n }\n };\n stdout.setEncoding(\"utf8\").on(\"data\", onChunk(\"stdout\"));\n stderr.setEncoding(\"utf8\").on(\"data\", onChunk(\"stderr\"));\n\n let forced = false;\n let exit: HostExit | undefined;\n const exited = new Promise<HostExit>((resolve) => {\n const done = (code: number | null, sig: NodeJS.Signals | null) => {\n if (exit) return;\n exit = { code, signal: sig, forced };\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(exit);\n };\n child.once(\"exit\", done);\n child.once(\"error\", (error) => {\n tail = (tail + `${error.message}\\n`).slice(-TAIL_BYTES);\n if (child.pid === undefined) done(null, null);\n });\n });\n\n // After the last chunk: stdio may still flush past \"exit\".\n const closed = new Promise<void>((resolve) => {\n child.once(\"close\", () => {\n log?.end();\n resolve();\n });\n });\n\n const pid = child.pid;\n const ownRecords = () =>\n pid === undefined\n ? []\n : listRunRecords(projectRoot, readerEnv).filter((r) => r.pid === pid);\n\n const kill = (sig: NodeJS.Signals) => {\n if (pid === undefined) return;\n try {\n process.kill(pid, sig);\n } catch {\n // already gone\n }\n };\n const clearOwnRecords = () => {\n for (const record of ownRecords()) {\n clearRunRecord(projectRoot, recordKeyOf(record), readerEnv);\n }\n };\n\n let stopping: Promise<HostExit> | undefined;\n const stop = (): Promise<HostExit> => {\n stopping ??= (async () => {\n if (!exit) {\n // Its end is the request: the child's `ph run` stops as on SIGTERM.\n if (stopOnStdin) child.stdin?.end();\n else kill(\"SIGTERM\");\n let timer: NodeJS.Timeout | undefined;\n const timedOut = await Promise.race([\n exited.then(() => false),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(true), stopTimeoutMs);\n }),\n ]);\n clearTimeout(timer);\n if (timedOut) {\n forced = true;\n // A member's processes go with it: a store or server it started\n // would hold its files and ports otherwise.\n if (stopOnStdin && pid !== undefined) killTree(pid, \"SIGKILL\");\n else kill(\"SIGKILL\");\n }\n }\n const result = await exited;\n // A killed child skips its exit handler's record clear.\n clearOwnRecords();\n return result;\n })();\n return stopping;\n };\n\n function onAbort() {\n void stop();\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n const deadline = Date.now() + readyTimeoutMs;\n for (;;) {\n const aborted = signal?.aborted ?? false;\n // Before the record: a child killed after writing it leaves it behind.\n if (exit && !aborted) {\n clearOwnRecords();\n let timer: NodeJS.Timeout | undefined;\n await Promise.race([\n closed,\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, CLOSE_WAIT_MS);\n }),\n ]);\n clearTimeout(timer);\n const how =\n exit.signal !== null ? `signal ${exit.signal}` : `code ${exit.code}`;\n throw new SpawnHostError(\n `spawnHost: ph run ${options.host} exited (${how}) before writing its run record.`,\n \"exited\",\n tail,\n exit,\n );\n }\n const record = aborted ? undefined : ownRecords().at(0);\n if (record) {\n return {\n pid: record.pid,\n dataDir,\n record,\n outputs: record.outputs,\n members: record.members,\n exited,\n stop,\n };\n }\n if (aborted || Date.now() >= deadline) {\n const phase: SpawnHostPhase = aborted ? \"aborted\" : \"timeout\";\n const ended = tail === \"\" || tail.endsWith(\"\\n\") ? \"\" : \"\\n\";\n const ran = `${tail}${ended}${SPAWN_STOPPING_NOTE}\\n`;\n tail = \"\";\n const stopped = await stop();\n let timer: NodeJS.Timeout | undefined;\n await Promise.race([\n closed,\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, CLOSE_WAIT_MS);\n }),\n ]);\n clearTimeout(timer);\n throw new SpawnHostError(\n phase === \"aborted\"\n ? `spawnHost: aborted before ph run ${options.host} was ready.`\n : `spawnHost: ph run ${options.host} wrote no run record within ${readyTimeoutMs} ms.`,\n phase,\n // What it printed while stopping can't push out where it got to.\n ran + tail,\n stopped,\n );\n }\n await Promise.race([sleep(POLL_MS), exited]);\n }\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 dev` 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 type { HostPackage } from \"../host-ref.js\";\nimport { loadHost, moduleRootOf } from \"../host-loader.js\";\nimport { defaultUserDataDir } from \"../placeholders.js\";\nimport {\n isPidAlive,\n listRunRecords,\n probeRun,\n runRecordKey,\n} 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 /** How the project addresses it (`<package>/<host>` for a package's). */\n ref?: string;\n /** The package that supplies it. */\n package?: HostPackage;\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). In a host a\n * package supplies (`scope`), a bare name is that package's host first. */\nexport async function loadProducers(\n projectRoot: string,\n refs: readonly OutputRef[],\n scope?: HostPackage,\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, { scope });\n const specifier = loaded.host.runner.module;\n producers.set(folder, {\n folder,\n name: loaded.host.name,\n ...(loaded.ref !== undefined ? { ref: loaded.ref } : {}),\n ...(loaded.package ? { package: loaded.package } : {}),\n specifier,\n runner: await resolveRunnerModule(\n moduleRootOf(projectRoot, loaded),\n specifier,\n ),\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 info = producers.get(ref.host);\n const loaded = info && !(\"error\" in info) ? info : undefined;\n // How the project addresses the producer: what a compound's record\n // names its member by.\n const address = loaded?.ref ?? ref.host;\n const notRunning = `${consumer} needs outputs from host \"${address}\", which is not running. Start it first: ph run ${address} (or run a compound that includes it).`;\n // The producer's outputsSchema: an absent optional field omits the\n // consuming property instead of failing.\n const schema = loaded?.runner.outputsSchema;\n const withSchema =\n schema !== undefined && schema !== null ? { schema } : {};\n const standalone: { label: string; outputs: Record<string, unknown> }[] =\n [];\n if (ref.member === undefined && loaded) {\n const key = runRecordKey(loaded.name, loaded.package?.name);\n const probe = probeRun(projectRoot, key, 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, key, projectName, sibling);\n if (other.status === \"live\" && other.record.outputs) {\n standalone.push({\n label: `\"${loaded.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 === address &&\n (ref.member === undefined || key === ref.member),\n )\n .map(([key, member]) => ({\n label: `member \"${key}\" of \"${runRecordKey(record.host, record.package)}\"`,\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 \"${address}\", which runs as ${found.map((m) => m.label).join(\" and \")}; stop all but one, or run ${address} 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).\n * `package` is the root of the package that supplies the host being\n * resolved (`hostPackage`), else the project root. */\nexport function processResolveEnv(\n projectRoot: string,\n env: Readonly<Record<string, string | undefined>> = process.env,\n hostPackage?: HostPackage,\n): Pick<ResolveSources, \"env\" | \"builtins\"> {\n return {\n env,\n builtins: {\n userData: defaultUserDataDir(projectRoot, env),\n projectRoot: path.resolve(projectRoot),\n package: hostPackage?.root ?? 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 /** A foreground member's end, with its exit code. */\n exited?: PromiseLike<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 ...(isPromiseLike(live.exited) ? { exited: live.exited } : {}),\n };\n}\n","import { resolvePhDir } from \"@powerhousedao/shared/clis/ph-dir\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport {\n declaredGenericCompoundHostSchema,\n type ChildWrapper,\n type CompoundWiring,\n type HostDefinition,\n type MemberProcess,\n type RunnerKind,\n} from \"./host-schemas.js\";\nimport { applyChildWrapper, type MemberDraft } from \"./child-wrapper.js\";\nimport {\n closeProcessControlChannel,\n controlRecordOf,\n ensureProcessControlChannel,\n} from \"./control-channel.js\";\nimport { substituteBuiltinEnv } from \"./env-substitution.js\";\nimport { loadHost, moduleRootOf } from \"./host-loader.js\";\nimport { hostFileLabel, type HostPackage } from \"./host-ref.js\";\nimport { defaultUserDataDir } from \"./placeholders.js\";\nimport { declaresKey, outputSitesOf } from \"./resolve/declared.js\";\nimport { processResolveEnv, runnerOutputsSchema } from \"./resolve/node.js\";\nimport {\n memberForRef,\n planCompound,\n type CompoundPlan,\n} 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 runRecordKey,\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 packageBuildRefusal,\n resolveRunnerModule,\n RunnerError,\n validateDeclaredHost,\n validateHost,\n type MemberStatus,\n type RunnerContext,\n type RunnerIssue,\n type RunnerModule,\n} from \"./runner-resolver.js\";\nimport { spawnHost } from \"./spawn-host.js\";\nimport { STOP_ON_STDIN_ENV } from \"./stop-channel.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 unless a member runs in its own process: member\n * verbs start their servers (which hold the event loop) and return a\n * handle; the compound lives as long as they do. An own-process member is\n * `ph run <host>` as a child (spawnHost), handed its resolved host, stopped\n * through its stdin. A foreground member (a runner that exports\n * `foreground: true`, the Cli runner) owns the terminal: it starts last, in\n * this process, and its end ends the stack with its exit code; the members\n * next to it run in their own processes unless they say otherwise.\n *\n * A compound an installed package supplies (`ctx.hostPackage`) names its\n * members in that package first: a bare member host is the package's when\n * it ships one, else the project's. Its record and its members' logs go in a\n * folder named after the package.\n */\n\ninterface StartedMember {\n name: string;\n member: ChildWrapper;\n /** How the project addresses the member's host (PreparedMember.ref). */\n ref: string;\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 /** How the project addresses the member's host: its folder, or\n * `<package>/<host>` for one a package supplies. An own-process member is\n * started by it, and the record names the member's host by it. */\n ref: string;\n /** The package that supplies the member's host. */\n hostPackage?: HostPackage;\n}\n\n/** `scope`: the package whose compound names the member (rule 3, D5). */\nexport async function memberDraft(\n projectRoot: string,\n member: ChildWrapper,\n scope?: HostPackage,\n): Promise<MemberDraft> {\n return applyChildWrapper(\n (await loadHost(projectRoot, member.host, { scope })).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\nexport { STOP_ON_STDIN_ENV };\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 HoldStopOptions {\n /** How long the stop may take before exiting regardless (default\n * {@link STOP_STREAM_LIMIT_MS}). */\n limitMs?: number;\n /** What the supervisor reads (default stdout and stderr). */\n outputs?: readonly NodeJS.WritableStream[];\n /** Delivers the request; false when nothing handles it (default: SIGTERM\n * to this process's handlers). */\n signal?: () => boolean;\n exit?: (code: number) => void;\n}\n\n/**\n * A standalone host's stop through its supervisor's stream (stdin, under\n * {@link STOP_ON_STDIN_ENV}): a line or the end of it is delivered as the\n * stop channel delivers a request, to the SIGTERM handlers, else as exit\n * 143. Held until `started()`: a stop while the verb starts takes effect\n * once it has, so a store is never left half-opened.\n */\nexport function holdStopRequests(\n stream: NodeJS.ReadableStream,\n options: HoldStopOptions = {},\n): { started(): void } {\n const exit = options.exit ?? ((code: number) => process.exit(code));\n const signal = options.signal ?? (() => process.emit(\"SIGTERM\", \"SIGTERM\"));\n let asked = false;\n let up = false;\n const deliver = () => {\n // No supervisor may be left to end a stop that hangs.\n const limit = options.limitMs ?? STOP_STREAM_LIMIT_MS;\n setTimeout(() => exit(143), limit).unref();\n if (!signal()) exit(143);\n };\n whenStreamStops(stream, () => {\n asked = true;\n if (up) deliver();\n });\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 asked for.\n for (const output of options.outputs ?? [process.stdout, process.stderr]) {\n output.on(\"error\", () => undefined);\n }\n return {\n started() {\n if (up) return;\n up = true;\n if (asked) deliver();\n },\n };\n}\n\n/** How long an own-process member may take to write its run record: a\n * store's first boot can be slow, and an in-process member has no limit. */\nexport const MEMBER_READY_TIMEOUT_MS = 600_000;\n\n/** Per-run log files kept per own-process member (the services manager's\n * number). */\nconst MEMBER_RUN_LOGS = 5;\n\n/** An id as a file name (the services manager's rule: `:` is no file name\n * on NTFS). */\nconst fileSafe = (id: string) => id.replace(/[<>:\"/\\\\|?*]/g, \"+\");\n\n/**\n * A fresh log file for this run of an own-process member, named as the\n * services manager names a service's: `<phDir>/services/<member>/\n * <member>.<runId>.log`, or `<phDir>/services/<package>/<member>/…` for a\n * compound the package `hostPackage` supplies. Older runs beyond the newest\n * few are removed.\n */\nexport function memberLogFile(\n projectRoot: string,\n env: Readonly<Record<string, string | undefined>>,\n member: string,\n hostPackage?: string,\n): string {\n const safe = fileSafe(member);\n const dir = path.join(\n resolvePhDir(projectRoot, env),\n \"services\",\n ...(hostPackage === undefined ? [] : hostPackage.split(\"/\")),\n safe,\n );\n fs.mkdirSync(dir, { recursive: true });\n const escaped = safe.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const pattern = new RegExp(`^${escaped}\\\\.(\\\\d+)\\\\.log$`);\n const runId = (name: string) => Number(pattern.exec(name)?.[1]);\n const runs = fs\n .readdirSync(dir)\n .filter((name) => pattern.test(name))\n .sort((a, b) => runId(b) - runId(a));\n for (const old of runs.slice(MEMBER_RUN_LOGS - 1)) {\n try {\n fs.rmSync(path.join(dir, old));\n } catch {\n // in use, or gone\n }\n }\n // Past the newest run seen: a run removed above must not lend its id to\n // one started within the same millisecond.\n let id = Math.max(Date.now(), runs.length > 0 ? runId(runs[0]) + 1 : 0);\n while (fs.existsSync(path.join(dir, `${safe}.${id}.log`))) id += 1;\n return path.join(dir, `${safe}.${id}.log`);\n}\n\n/** Every URL among a member's outputs, by dotted path. */\nexport function urlEndpoints(outputs: unknown): Record<string, string> {\n const found: Record<string, string> = {};\n const walk = (value: unknown, at: string) => {\n if (typeof value === \"string\") {\n if (/^[a-z][a-z\\d+.-]*:\\/\\//i.test(value)) found[at] = value;\n } else if (Array.isArray(value)) {\n value.forEach((item, i) => walk(item, at ? `${at}.${i}` : String(i)));\n } else if (isPlainObject(value)) {\n for (const [key, item] of Object.entries(value)) {\n walk(item, at ? `${at}.${key}` : key);\n }\n }\n };\n walk(outputs, \"\");\n return found;\n}\n\n/** A member as {@link planForeground} reads it. */\nexport interface ForegroundCandidate {\n key: string;\n specifier: string;\n member: Pick<ChildWrapper, \"process\">;\n runner: Pick<RunnerModule, \"foreground\">;\n}\n\nexport interface ForegroundPlan {\n /** The member whose runner owns the terminal, when there is one. */\n foreground?: string;\n /** The start order: the plan's, with the foreground member last. */\n order: string[];\n /** Broken foreground rules; `ph run` refuses the first. */\n issues: RunnerIssue[];\n}\n\n/**\n * The member whose runner owns the terminal (`foreground: true`) and the\n * order the compound starts its members in. Its rules: one such member at\n * most, in the compound's process, and last, so no member reads its outputs\n * and a `startOrder` that names it puts it at the end. `runCompound` refuses\n * the first broken one; `ph host check` reports them all.\n */\nexport function planForeground(\n members: readonly ForegroundCandidate[],\n plan: CompoundPlan,\n wiring: CompoundWiring,\n): ForegroundPlan {\n const owners = members.filter((m) => m.runner.foreground === true);\n if (owners.length === 0) return { order: plan.order, issues: [] };\n if (owners.length > 1) {\n return {\n order: plan.order,\n issues: [\n {\n path: \"children\",\n message: `members ${owners.map((m) => `\"${m.key}\"`).join(\", \")} each run a runner that owns the terminal; a compound has one.`,\n },\n ],\n };\n }\n const [owner] = owners;\n const where = `member \"${owner.key}\" (${owner.specifier})`;\n const issues: RunnerIssue[] = [];\n if (owner.member.process === \"own\") {\n issues.push({\n path: `children.${owner.key}.process`,\n message: `${where} owns the terminal, so it runs in the compound's process, not its own.`,\n hint: `Remove children.${owner.key}.process.`,\n });\n }\n const readers = plan.edges.filter((edge) => edge.producer === owner.key);\n if (readers.length > 0) {\n issues.push({\n path: \"children\",\n message: `${readers.map((edge) => `${edge.consumer}.${edge.path}`).join(\", \")} read the outputs of ${where}, which owns the terminal and starts last.`,\n });\n }\n const named = wiring.startOrder;\n if (named?.includes(owner.key) && named.at(-1) !== owner.key) {\n issues.push({\n path: \"config.startOrder\",\n message: `config.startOrder starts ${where} before ${named.slice(named.indexOf(owner.key) + 1).join(\", \")}, but it owns the terminal and starts last.`,\n hint: \"Put it last in startOrder, or leave it out.\",\n });\n }\n return {\n foreground: owner.key,\n order: [...plan.order.filter((key) => key !== owner.key), owner.key],\n issues,\n };\n}\n\n/** Where a member runs: `own` (a child process) or `shared` (the\n * compound's). The foreground member and every member at a one-shot verb\n * share the compound's; next to a foreground member the default is `own`. */\nexport function memberProcessOf(\n member: Pick<ChildWrapper, \"process\">,\n options: {\n /** It is the foreground member. */\n foreground: boolean;\n /** The compound has a foreground member. */\n besideForeground: boolean;\n /** It runs at a one-shot verb (build). */\n oneShot: boolean;\n },\n): MemberProcess {\n if (options.foreground || options.oneShot) return \"shared\";\n return member.process ?? (options.besideForeground ? \"own\" : \"shared\");\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 // The package that supplies this compound: its members are its first.\n const scope = ctx.hostPackage;\n const compoundFile = scope\n ? `${scope.name}/hosts/${hostInput.name}`\n : `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\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 recordKey = runRecordKey(host.name, scope?.name);\n const probe = oneShotCompound\n ? undefined\n : probeRun(projectRoot, recordKey, options.projectName);\n const live = probe?.status === \"live\" ? probe.record : undefined;\n const running = live\n ? new Error(\n `${recordKey} is already running for this project (pid ${live.pid}). ` +\n `Stop it before starting another.`,\n )\n : undefined;\n // Only a command for its foreground member may run beside it (below).\n if (running && (ctx.argv ?? []).length === 0) throw running;\n if (probe?.status === \"foreign\") {\n throw new Error(\n `.ph/run/${recordKey}.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 let prepared: PreparedMember[];\n let order: string[];\n let foreground: string | undefined;\n let memberArgv: Map<string, string[]>;\n const byKey = new Map<string, PreparedMember>();\n try {\n prepared = await prepareMembers(projectRoot, host.children, scope);\n const cycle = await memberCycle(projectRoot, prepared);\n if (cycle) {\n throw new RunnerError(\n `${compoundFile}: compound member cycle: ${cycle.join(\" -> \")}.`,\n \"A compound cannot run itself, directly or through another compound.\",\n );\n }\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 for (const m of prepared) byKey.set(m.key, m);\n const declared = 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, declared);\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 : {\n error: `names member \"${target.key}\", which was not prepared.`,\n };\n },\n });\n }\n const planned = planForeground(prepared, plan, wiring);\n const broken = planned.issues.at(0);\n if (broken) {\n throw new RunnerError(`${compoundFile}: ${broken.message}`, broken.hint);\n }\n foreground = planned.foreground;\n order = planned.order;\n\n // A package's hosts are built by the package: a build here would write\n // into the installed package. Refused before any member builds; the\n // foreground member, which a build skips, does not count.\n if (oneShotCompound) {\n const supplied = scope\n ? [{ ref: recordKey, hostPackage: scope, where: compoundFile }]\n : prepared.flatMap((m) =>\n m.hostPackage && m.key !== foreground\n ? [\n {\n ref: m.ref,\n hostPackage: m.hostPackage,\n where: `${compoundFile} (member \"${m.key}\")`,\n },\n ]\n : [],\n );\n const [first] = supplied;\n if (first) {\n const refusal = packageBuildRefusal(first.ref, first.hostPackage, verb);\n throw new RunnerError(\n `${first.where}: ${refusal.message}`,\n refusal.hint,\n );\n }\n }\n\n // This invocation's arguments, per member: one no member accepts fails\n // with nothing running.\n 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 foreground,\n );\n } catch (error) {\n // A running instance is what stands in the way, whatever else is wrong.\n throw running ?? error;\n }\n // A command beside the running instance: its foreground member alone, on\n // the outputs the live record holds. Nothing else of it starts, and there\n // is no lock to take or record to write.\n const beside = running !== undefined;\n if (\n running &&\n (foreground === undefined ||\n (memberArgv.get(foreground) ?? []).length === 0)\n ) {\n throw running;\n }\n const keepsRecord =\n wiring.runtimeRecord !== false && !oneShotCompound && !beside;\n const members = prepared.map((m) => ({ key: m.key, host: m.member.host }));\n // A stack with a terminal answers commands typed beside it: the channel\n // opens before the foreground member starts, which answers on it.\n const control =\n keepsRecord && foreground !== undefined\n ? (await ensureProcessControlChannel())?.record\n : undefined;\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 for (const [key, member] of Object.entries(live?.members ?? {})) {\n liveOutputs.set(key, member.outputs);\n }\n const outputs = compoundOutputSource(\n members,\n liveOutputs,\n host.name,\n new Map(prepared.map((m) => [m.key, m.runner.outputsSchema])),\n );\n // Per member: `${package}` is the root of the package that supplies the\n // member's host, the project root for a project member.\n const resolveEnvOf = (m: PreparedMember) =>\n processResolveEnv(projectRoot, ctx.env, m.hostPackage);\n // What the foreground member is shown of the others.\n const statuses = new Map<string, MemberStatus>();\n const othersSeen = (): MemberStatus[] =>\n [...statuses.values()]\n .filter((status) => status.name !== foreground)\n .map((status) => ({ ...status, endpoints: { ...status.endpoints } }));\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 const status = statuses.get(m.name);\n if (status?.status === \"starting\" || status?.status === \"ready\") {\n status.status = \"stopping\";\n }\n try {\n await m.handle.shutdown?.();\n } catch {\n // best effort — keep tearing down the rest\n }\n if (status?.status === \"stopping\") status.status = \"stopped\";\n }\n if (keepsRecord) clearRunRecord(projectRoot, recordKey);\n if (control) await closeProcessControlChannel();\n })());\n\n // An own-process member that died on its own: what to print, and (once the\n // stack is up) what ends it. Before that, the start fails on it.\n const death: { message?: string; ends?: () => void } = {};\n\n try {\n for (const name of order) {\n if (death.message) throw new Error(death.message);\n const m = byKey.get(name);\n if (!m) continue;\n const isForeground = name === foreground;\n // Beside a running instance only its foreground member starts. The\n // foreground member is the stack's terminal: it runs at its own\n // default verb, and at a one-shot verb (build) it has nothing to do.\n if (beside && !isForeground) continue;\n if (isForeground && oneShotCompound) continue;\n const memberVerb = isForeground\n ? (m.draft.runner.defaultVerb ?? \"run\")\n : memberVerbOf(verb, m.draft.runner);\n const oneShot = ONE_SHOT_VERBS.has(memberVerb);\n const memberProcess = memberProcessOf(m.member, {\n foreground: isForeground,\n besideForeground: foreground !== undefined,\n oneShot,\n });\n // A one-shot member (build) needs no other member's outputs: it gets\n // its declared host with only the \"${userData}\"/\"${projectRoot}\"/\n // \"${package}\" string sugar substituted (tokens stay; its verb reads\n // paths, never outputs; a $map reaches the verb as an empty\n // collection). Everything else resolves against the members started\n // before it and is validated in resolved form.\n const resolveEnv = resolveEnvOf(m);\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 status: MemberStatus = {\n name,\n host: m.ref,\n process: memberProcess,\n status: \"starting\",\n endpoints: {},\n };\n statuses.set(name, status);\n let handle: StartedHandle;\n if (memberProcess === \"own\") {\n // Ready once its record is written: its `ready` has resolved.\n const own = await startOwnProcess({\n projectRoot,\n compound: host.name,\n member: name,\n // As the project addresses it: a bare name in a package's compound\n // may be the package's host, which the child's `ph run` must get.\n folder: m.ref,\n verb: memberVerb,\n argv,\n env: ctx.env,\n host: resolved,\n // In-process members print here too; next to the terminal's\n // owner, output would draw into it.\n echo: foreground === undefined,\n ...(scope ? { logPackage: scope.name } : {}),\n });\n handle = own.handle;\n status.pid = own.pid;\n status.logFile = own.logFile;\n void own.exited.then((exit) => {\n // Only an exit the compound did not ask for (it marks a member\n // `stopping` before it stops it).\n if (status.status !== \"starting\" && status.status !== \"ready\") {\n return;\n }\n status.status = exit.code === 0 ? \"stopped\" : \"failed\";\n const how =\n exit.signal !== null\n ? `signal ${exit.signal}`\n : `code ${exit.code}`;\n status.error = `exited (${how}) while the stack runs; its log: ${own.logFile}`;\n // A long-running member that ends, whatever its code, fails the\n // stack.\n death.message ??= `${compoundFile}: member \"${name}\" ${status.error}`;\n death.ends?.();\n });\n } else {\n handle = toStartedHandle(\n await fn(oneShot ? emptyMaps(validated, resolved) : validated, {\n projectRoot,\n ...(m.hostPackage ? { hostPackage: m.hostPackage } : {}),\n env: ctx.env,\n verb: memberVerb,\n parent: { host: host.name, verb },\n ...(argv.length > 0 ? { argv } : {}),\n ...(isForeground\n ? {\n foreground: {\n members: othersSeen,\n beside,\n stack: recordKey,\n ...(beside && controlRecordOf(live)\n ? { control: controlRecordOf(live) }\n : {}),\n },\n }\n : {}),\n }),\n where,\n );\n status.pid = process.pid;\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 ref: m.ref,\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 if (status.status === \"starting\") status.status = \"ready\";\n status.endpoints = urlEndpoints(memberOutputs);\n }\n if (death.message) throw new Error(death.message);\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.ref,\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 ...(scope ? { package: scope.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 || control\n ? { extra: { ...options.recordExtra, ...(control ? { control } : {}) } }\n : {}),\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 // The first end decides the code: a signal's, or the foreground member's.\n const exit = options.exit ?? ((code: number) => process.exit(code));\n let ending: Promise<void> | undefined;\n const end = (code: number, afterStop?: () => void) =>\n (ending ??= shutdown().finally(() => {\n afterStop?.();\n exit(code);\n }));\n const handleSignal = (signal: \"SIGINT\" | \"SIGTERM\") =>\n end(signal === \"SIGINT\" ? 130 : 143);\n if (options.installSignalHandlers !== false) {\n process.on(\"exit\", () => {\n if (keepsRecord) clearRunRecord(projectRoot, recordKey);\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 // A member that dies on its own takes the stack down with exit code 1. The\n // message waits until the others (the terminal's owner first) have stopped,\n // so it does not land in a drawing.\n death.ends = () => void end(1, () => console.error(death.message));\n // One that died between the last check above and here.\n if (death.message) death.ends();\n\n // The foreground member's end is the stack's: the rest stop, and the\n // process exits with its code.\n const exited = started.find((m) => m.name === foreground)?.handle.exited;\n if (exited) {\n Promise.resolve(exited).then(\n (code) => void end(typeof code === \"number\" ? code : 0),\n () => void end(1),\n );\n }\n\n return { started, shutdown, handleSignal };\n}\n\ninterface OwnProcessStart {\n projectRoot: string;\n compound: string;\n member: string;\n folder: string;\n verb: string;\n argv: readonly string[];\n env: Readonly<Record<string, string | undefined>>;\n /** The member's host, resolved: what the child runs. */\n host: Record<string, unknown>;\n /** Also write its output to this process's stdout and stderr. */\n echo: boolean;\n /** The package that supplies the compound: its members' logs are in a\n * folder named after it. */\n logPackage?: string;\n}\n\n/**\n * An own-process member: `ph run <folder> <verb> -- <argv>` as an attached,\n * hidden child (spawnHost) with the compound's env, its resolved host and a\n * stdin it stops on; its output in this run's log file. Resolves once its\n * run record is written, which its `ph run` does after `ready`.\n */\nasync function startOwnProcess(start: OwnProcessStart) {\n const logFile = memberLogFile(\n start.projectRoot,\n start.env,\n start.member,\n start.logPackage,\n );\n const spawned = await spawnHost({\n projectRoot: start.projectRoot,\n host: start.folder,\n // The compound's own: the member's stores and record are where they\n // would be in the compound's process.\n dataDir: defaultUserDataDir(start.projectRoot, start.env),\n verb: start.verb,\n argv: start.argv,\n baseEnv: start.env,\n definition: {\n compound: start.compound,\n member: start.member,\n host: start.host,\n },\n stopOnStdin: true,\n logFile,\n readyTimeoutMs: MEMBER_READY_TIMEOUT_MS,\n ...(start.echo\n ? {\n onOutput: (stream: \"stdout\" | \"stderr\", chunk: string) => {\n process[stream].write(chunk);\n },\n }\n : {}),\n });\n const handle: StartedHandle = {\n outputs: spawned.outputs ?? {},\n shutdown: () => spawned.stop(),\n };\n return { handle, pid: spawned.pid, logFile, exited: spawned.exited };\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 scope?: HostPackage,\n): Promise<PreparedMember[]> {\n const out: PreparedMember[] = [];\n for (const [key, member] of Object.entries(children)) {\n out.push(await prepareMember(projectRoot, key, member, scope));\n }\n return out;\n}\n\n/** One member's draft and runner. `scope`: the package whose compound names\n * the member, where a bare member host is looked up first; the runner\n * resolves from the package that supplies the member's host. */\nexport async function prepareMember(\n projectRoot: string,\n key: string,\n member: ChildWrapper,\n scope?: HostPackage,\n): Promise<PreparedMember> {\n const loaded = await loadHost(projectRoot, member.host, { scope });\n const draft = applyChildWrapper(loaded.host, member);\n const specifier = draft.runner.module;\n return {\n key,\n member,\n draft,\n specifier,\n runner: await resolveRunnerModule(\n moduleRootOf(projectRoot, loaded),\n specifier,\n ),\n file: hostFileLabel(loaded.name, loaded.package),\n ref: loaded.ref ?? member.host,\n ...(loaded.package ? { hostPackage: loaded.package } : {}),\n };\n}\n\n/**\n * A compound that is, through its compound members, a member of itself\n * would start itself without end: the chain of hosts, as the project\n * addresses them, when there is one. Each compound member's own members are\n * looked up as it looks them up (its package first, for a package's). A\n * reactor member ends a chain.\n */\nexport async function memberCycle(\n projectRoot: string,\n prepared: readonly PreparedMember[],\n): Promise<string[] | undefined> {\n const walk = async (\n chain: string[],\n children: Record<string, ChildWrapper>,\n scope: HostPackage | undefined,\n ): Promise<string[] | undefined> => {\n for (const member of Object.values(children)) {\n const loaded = await loadHost(projectRoot, member.host, { scope });\n const ref = loaded.ref ?? member.host;\n if (chain.includes(ref)) return [...chain, ref];\n const nested = (loaded.host as { children?: unknown }).children;\n if (!isPlainObject(nested)) continue;\n const found = await walk(\n [...chain, ref],\n nested as Record<string, ChildWrapper>,\n loaded.package,\n );\n if (found) return found;\n }\n return undefined;\n };\n for (const m of prepared) {\n const nested = (m.draft as { children?: unknown }).children;\n if (!isPlainObject(nested)) continue;\n const found = await walk(\n [m.ref],\n nested as Record<string, ChildWrapper>,\n m.hostPackage,\n );\n if (found) return found;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAgB,4BACd,UACA;CACA,OAAO,EAAE,aAAa;EACpB,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;EACtB,IAAI,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;;;;;;EAM/B,aAAa,EAAE,MAAM,CAAC,EAAE,QAAQ,G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