@powerhousedao/host-core 6.2.3-dev.57 → 6.2.3-dev.59

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,127 @@
1
+ import { z } from "zod";
2
+ //#region src/plugins.d.ts
3
+ /**
4
+ * R1 — the host plugin framework (bridge-runners-to-plugins plan,
5
+ * customization-references/host-core as the blueprint).
6
+ *
7
+ * A plugin is hooks + contributions; hooks are boot wiring (main realm only),
8
+ * contributions are declarative, serializable surface. Host RUNTIMES define
9
+ * the hook vocabulary and interleave their own wiring between stages — they
10
+ * are never plugins themselves.
11
+ *
12
+ * host.js carries the COMPOSITION as `runner.plugins` entries:
13
+ * string | { module, enabled?, verbs?, config? }
14
+ * Presence is activation (enabled defaults true); `verbs` scopes an entry to
15
+ * matching run verbs; `config` is validated against the plugin's declared
16
+ * zod schema. Entries resolve from the PROJECT's dependency tree exactly
17
+ * like runner modules.
18
+ */
19
+ export declare class PluginError extends Error {
20
+ constructor(message: string, hint?: string);
21
+ }
22
+ export declare const pluginEntryObjectSchema: z.ZodObject<{
23
+ module: z.ZodString;
24
+ /** Presence is activation BY DEFAULT; false is the explicit off-switch. */
25
+ enabled: z.ZodOptional<z.ZodBoolean>;
26
+ /** "*" (default) or the run verbs this entry is active for. */
27
+ verbs: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"*">, z.ZodArray<z.ZodString>]>>;
28
+ /** Validated against the plugin's declared configSchema at resolution. */
29
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
30
+ }, z.core.$strict>;
31
+ export declare const pluginEntrySchema: z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
32
+ module: z.ZodString;
33
+ /** Presence is activation BY DEFAULT; false is the explicit off-switch. */
34
+ enabled: z.ZodOptional<z.ZodBoolean>;
35
+ /** "*" (default) or the run verbs this entry is active for. */
36
+ verbs: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"*">, z.ZodArray<z.ZodString>]>>;
37
+ /** Validated against the plugin's declared configSchema at resolution. */
38
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
39
+ }, z.core.$strict>]>;
40
+ export type PluginEntry = z.infer<typeof pluginEntrySchema>;
41
+ export interface NormalizedPluginEntry {
42
+ module: string;
43
+ enabled: boolean;
44
+ verbs: "*" | string[];
45
+ config: Record<string, unknown>;
46
+ }
47
+ export declare function normalizePluginEntry(entry: PluginEntry): NormalizedPluginEntry;
48
+ /** Module is the identity key: a duplicate makes override targeting and
49
+ * ordering ambiguous, so it fails loudly. */
50
+ export declare function normalizePluginEntries(entries: readonly PluginEntry[], where: string): NormalizedPluginEntry[];
51
+ export declare function entryActiveForVerb(entry: NormalizedPluginEntry, verb: string): boolean;
52
+ export declare function registerHostType(id: string, parent: string | null): void;
53
+ export declare function hostTypeSatisfies(hostType: string, appliesTo: string): boolean;
54
+ /** Hook kinds (v1 §2.2). The hook VOCABULARY is defined by host runtimes;
55
+ * plugins implement subsets of it. */
56
+ export type Provide<T, C> = (ctx: C) => T | Promise<T>;
57
+ export type Transform<T, C> = (value: T, ctx: C) => T | Promise<T>;
58
+ export type Observe<C> = (ctx: C) => void | Promise<void>;
59
+ /**
60
+ * Core contributions — declarative, serializable, realm-crossing. Host
61
+ * runtimes extend this with their own kinds (UI slots live in connect-host,
62
+ * never here). `drives` entries use the drive declaration shape from
63
+ * drives.ts; kept as unknown here to avoid a cycle — the merge is shape-blind.
64
+ */
65
+ export interface Contributions {
66
+ drives?: unknown[];
67
+ packages?: string[];
68
+ configDeclarations?: {
69
+ name: string;
70
+ type?: string;
71
+ description?: string;
72
+ }[];
73
+ [kind: string]: unknown[] | undefined;
74
+ }
75
+ export interface HostPlugin<THooks = Record<string, unknown>, TConfig = unknown> {
76
+ /** Stable id; used in ordering, dependsOn, and every diagnostic. */
77
+ name: string;
78
+ /** Host-type requirement; the entry is rejected on a host outside the
79
+ * hierarchy branch. Default: "reactor". */
80
+ appliesTo?: string;
81
+ /** Coarse ordering bucket (Vite-style). Default: "normal". */
82
+ enforce?: "pre" | "post";
83
+ /** Hard dependencies on OTHER PLUGINS — the host runtime is implied and
84
+ * never named. Missing dependency or cycle fails boot naming both sides. */
85
+ dependsOn?: string[];
86
+ /** Declared config shape; entry config is validated against it. A plugin
87
+ * without a schema accepts no config (passing one is a boot error). */
88
+ configSchema?: z.ZodType<TConfig>;
89
+ hooks?: Partial<THooks>;
90
+ contributions?: Contributions;
91
+ }
92
+ /** A plugin module default-exports either a HostPlugin object (no config
93
+ * accepted) or a factory `(config) => HostPlugin`. */
94
+ export type HostPluginModule<THooks = Record<string, unknown>, TConfig = unknown> = HostPlugin<THooks, TConfig> | ((config: TConfig) => HostPlugin<THooks, TConfig>);
95
+ export interface ResolvedPlugin<THooks = Record<string, unknown>> {
96
+ entry: NormalizedPluginEntry;
97
+ plugin: HostPlugin<THooks>;
98
+ /** Provenance for contribution merge ordering. */
99
+ provenance: "built-in" | "local" | "dependency";
100
+ }
101
+ /** Registration order, bucketed pre → normal → post (stable within buckets),
102
+ * then dependsOn topo-sorted within the bucketed order. */
103
+ export declare function resolveOrder<THooks>(plugins: readonly HostPlugin<THooks>[]): HostPlugin<THooks>[];
104
+ export declare function runProvideHook<T, C>(name: string, plugins: readonly HostPlugin[], ctx: C): Promise<T | undefined>;
105
+ export declare function runTransformHook<T, C>(name: string, plugins: readonly HostPlugin[], ctx: C, seed: T): Promise<T>;
106
+ /** Sequential observe, in plugin order — for lifecycle moments whose order
107
+ * is load-bearing (teardown: the switchboard stops privacy before workflows
108
+ * before the api, per the carve map). */
109
+ export declare function runObserveHookSequential<C>(name: string, plugins: readonly HostPlugin[], ctx: C): Promise<void>;
110
+ export declare function runObserveHook<C>(name: string, plugins: readonly HostPlugin[], ctx: C): Promise<void>;
111
+ export interface ContributionSource {
112
+ pluginName: string;
113
+ provenance: "built-in" | "local" | "dependency";
114
+ }
115
+ export interface MergedContribution<T = unknown> {
116
+ value: T;
117
+ source: ContributionSource;
118
+ }
119
+ /** Array kinds concatenate in provenance-then-order sequence (built-in first,
120
+ * so later sources read as overrides where consumers want last-wins). */
121
+ export declare function mergeContributions(resolved: readonly {
122
+ plugin: HostPlugin;
123
+ provenance: ContributionSource["provenance"];
124
+ }[]): Record<string, MergedContribution[]>;
125
+ //#endregion
126
+ export {};
127
+ //# sourceMappingURL=plugins.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugins.d.mts","names":[],"sources":["../src/plugins.ts"],"mappings":";;;;;;;;;;;;;;;;;;qBAmBa,oBAAoB;EAC/B,YAAY,iBAAiB;;qBAQlB,yBAAuB,EAAA;;;;;;;;GAUlC,EAAA,KAAA;qBAEW,mBAAiB,EAAA,mBAAA,EAAA,WAAA,EAAA;;;;;;;;GAG5B,EAAA,KAAA;YAEU,cAAc,EAAE,aAAa;iBAExB;EACf;EACA;EACA;EACA,QAAQ;;wBAGM,qBACd,OAAO,cACN;;;wBAca,uBACd,kBAAkB,eAClB,gBACC;wBAea,mBACd,OAAO,uBACP;wBAsBc,iBAAiB,YAAY;wBAS7B,kBACd,kBACA;;;YAcU,QAAQ,GAAG,MAAM,KAAK,MAAM,IAAI,QAAQ;YACxC,UAAU,GAAG,MAAM,OAAO,GAAG,KAAK,MAAM,IAAI,QAAQ;YACpD,QAAQ,MAAM,KAAK,aAAa;;;;;;;iBAQ3B;EACf;EACA;EACA;IAAuB;IAAc;IAAe;;GACnD;;iBAGc,WACf,SAAS,yBACT;;EAGA;;;EAGA;;EAEA;;;EAGA;;;EAGA,eAAe,EAAE,QAAQ;EACzB,QAAQ,QAAQ;EAChB,gBAAgB;;;;YAKN,iBACV,SAAS,yBACT,qBAEE,WAAW,QAAQ,aACjB,QAAQ,YAAY,WAAW,QAAQ;iBAE5B,eAAe,SAAS;EACvC,OAAO;EACP,QAAQ,WAAW;;EAEnB;;;;wBAOc,aAAa,QAC3B,kBAAkB,WAAW,YAC5B,WAAW;wBA6CQ,eAAe,GAAG,GACtC,cACA,kBAAkB,cAClB,KAAK,IACJ,QAAQ;wBAWW,iBAAiB,GAAG,GACxC,cACA,kBAAkB,cAClB,KAAK,GACL,MAAM,IACL,QAAQ;;;;wBAYW,yBAAyB,GAC7C,cACA,kBAAkB,cAClB,KAAK,IACJ;wBAOmB,eAAe,GACnC,cACA,kBAAkB,cAClB,KAAK,IACJ;iBAWc;EACf;EACA;;iBAGe,mBAAmB;EAClC,OAAO;EACP,QAAQ;;;;wBAKM,mBACd;EACE,QAAQ;EACR,YAAY;MAEb,eAAe"}
@@ -0,0 +1,174 @@
1
+ import { z } from "zod";
2
+ //#region src/plugins.ts
3
+ /**
4
+ * R1 — the host plugin framework (bridge-runners-to-plugins plan,
5
+ * customization-references/host-core as the blueprint).
6
+ *
7
+ * A plugin is hooks + contributions; hooks are boot wiring (main realm only),
8
+ * contributions are declarative, serializable surface. Host RUNTIMES define
9
+ * the hook vocabulary and interleave their own wiring between stages — they
10
+ * are never plugins themselves.
11
+ *
12
+ * host.js carries the COMPOSITION as `runner.plugins` entries:
13
+ * string | { module, enabled?, verbs?, config? }
14
+ * Presence is activation (enabled defaults true); `verbs` scopes an entry to
15
+ * matching run verbs; `config` is validated against the plugin's declared
16
+ * zod schema. Entries resolve from the PROJECT's dependency tree exactly
17
+ * like runner modules.
18
+ */
19
+ var PluginError = class extends Error {
20
+ constructor(message, hint) {
21
+ super(hint ? `${message}\n Hint: ${hint}` : message);
22
+ this.name = "PluginError";
23
+ }
24
+ };
25
+ const pluginEntryObjectSchema = z.strictObject({
26
+ module: z.string().min(1),
27
+ /** Presence is activation BY DEFAULT; false is the explicit off-switch. */
28
+ enabled: z.boolean().optional(),
29
+ /** "*" (default) or the run verbs this entry is active for. */
30
+ verbs: z.union([z.literal("*"), z.array(z.string().min(1)).min(1)]).optional(),
31
+ /** Validated against the plugin's declared configSchema at resolution. */
32
+ config: z.record(z.string(), z.unknown()).optional()
33
+ });
34
+ const pluginEntrySchema = z.union([z.string().min(1), pluginEntryObjectSchema]);
35
+ function normalizePluginEntry(entry) {
36
+ if (typeof entry === "string") return {
37
+ module: entry,
38
+ enabled: true,
39
+ verbs: "*",
40
+ config: {}
41
+ };
42
+ return {
43
+ module: entry.module,
44
+ enabled: entry.enabled ?? true,
45
+ verbs: entry.verbs ?? "*",
46
+ config: entry.config ?? {}
47
+ };
48
+ }
49
+ /** Module is the identity key: a duplicate makes override targeting and
50
+ * ordering ambiguous, so it fails loudly. */
51
+ function normalizePluginEntries(entries, where) {
52
+ const normalized = entries.map(normalizePluginEntry);
53
+ const seen = /* @__PURE__ */ new Set();
54
+ for (const entry of normalized) {
55
+ if (seen.has(entry.module)) throw new PluginError(`${where}: plugin "${entry.module}" is listed twice.`, "Module specifiers are the identity key of a composition; a plugin meant to run twice needs distinct subpath specifiers.");
56
+ seen.add(entry.module);
57
+ }
58
+ return normalized;
59
+ }
60
+ function entryActiveForVerb(entry, verb) {
61
+ if (!entry.enabled) return false;
62
+ return entry.verbs === "*" || entry.verbs.includes(verb);
63
+ }
64
+ /**
65
+ * The appliesTo hierarchy. "reactor" is the base every reactor host extends;
66
+ * "compound" is its own branch (plugins over the member set — e.g. the clint
67
+ * proxy). Host runtimes register their id with a parent; compatibility walks
68
+ * the parent chain.
69
+ */
70
+ const HOST_TYPE_PARENTS = {
71
+ reactor: null,
72
+ compound: null,
73
+ connect: "reactor",
74
+ switchboard: "reactor",
75
+ mastra: "reactor"
76
+ };
77
+ function registerHostType(id, parent) {
78
+ if (id in HOST_TYPE_PARENTS && HOST_TYPE_PARENTS[id] !== parent) throw new PluginError(`Host type "${id}" is already registered with parent "${String(HOST_TYPE_PARENTS[id])}".`);
79
+ HOST_TYPE_PARENTS[id] = parent;
80
+ }
81
+ function hostTypeSatisfies(hostType, appliesTo) {
82
+ let current = hostType;
83
+ while (current !== null) {
84
+ if (current === appliesTo) return true;
85
+ current = current in HOST_TYPE_PARENTS ? HOST_TYPE_PARENTS[current] : null;
86
+ }
87
+ return false;
88
+ }
89
+ /** Registration order, bucketed pre → normal → post (stable within buckets),
90
+ * then dependsOn topo-sorted within the bucketed order. */
91
+ function resolveOrder(plugins) {
92
+ const buckets = {
93
+ pre: [],
94
+ normal: [],
95
+ post: []
96
+ };
97
+ for (const plugin of plugins) buckets[plugin.enforce ?? "normal"].push(plugin);
98
+ const bucketed = [
99
+ ...buckets.pre,
100
+ ...buckets.normal,
101
+ ...buckets.post
102
+ ];
103
+ const byName = new Map(bucketed.map((p) => [p.name, p]));
104
+ for (const plugin of bucketed) for (const dep of plugin.dependsOn ?? []) if (!byName.has(dep)) throw new PluginError(`Plugin "${plugin.name}" depends on missing plugin "${dep}".`, "dependsOn names PLUGINS only — the host runtime is implied and never named.");
105
+ const ordered = [];
106
+ const state = /* @__PURE__ */ new Map();
107
+ const visit = (plugin, chain) => {
108
+ const mark = state.get(plugin.name);
109
+ if (mark === "done") return;
110
+ if (mark === "visiting") throw new PluginError(`Plugin dependency cycle: ${[...chain, plugin.name].join(" -> ")}.`);
111
+ state.set(plugin.name, "visiting");
112
+ for (const dep of plugin.dependsOn ?? []) visit(byName.get(dep), [...chain, plugin.name]);
113
+ state.set(plugin.name, "done");
114
+ ordered.push(plugin);
115
+ };
116
+ for (const plugin of bucketed) visit(plugin, []);
117
+ return ordered;
118
+ }
119
+ async function runProvideHook(name, plugins, ctx) {
120
+ const impls = plugins.filter((p) => typeof p.hooks?.[name] === "function");
121
+ if (impls.length > 1) throw new PluginError(`Hook "${name}" is provided by ${impls.map((p) => `"${p.name}"`).join(" and ")} — provide hooks have one winner.`);
122
+ const impl = impls[0]?.hooks?.[name];
123
+ return impl ? await impl(ctx) : void 0;
124
+ }
125
+ async function runTransformHook(name, plugins, ctx, seed) {
126
+ let value = seed;
127
+ for (const plugin of plugins) {
128
+ const impl = plugin.hooks?.[name];
129
+ if (typeof impl === "function") value = await impl(value, ctx);
130
+ }
131
+ return value;
132
+ }
133
+ /** Sequential observe, in plugin order — for lifecycle moments whose order
134
+ * is load-bearing (teardown: the switchboard stops privacy before workflows
135
+ * before the api, per the carve map). */
136
+ async function runObserveHookSequential(name, plugins, ctx) {
137
+ for (const plugin of plugins) {
138
+ const impl = plugin.hooks?.[name];
139
+ if (typeof impl === "function") await impl(ctx);
140
+ }
141
+ }
142
+ async function runObserveHook(name, plugins, ctx) {
143
+ await Promise.all(plugins.map(async (plugin) => {
144
+ const impl = plugin.hooks?.[name];
145
+ if (typeof impl === "function") await impl(ctx);
146
+ }));
147
+ }
148
+ /** Array kinds concatenate in provenance-then-order sequence (built-in first,
149
+ * so later sources read as overrides where consumers want last-wins). */
150
+ function mergeContributions(resolved) {
151
+ const rank = {
152
+ "built-in": 0,
153
+ local: 1,
154
+ dependency: 2
155
+ };
156
+ const sorted = [...resolved].sort((a, b) => rank[a.provenance] - rank[b.provenance]);
157
+ const merged = {};
158
+ for (const { plugin, provenance } of sorted) for (const [kind, values] of Object.entries(plugin.contributions ?? {})) {
159
+ if (!values) continue;
160
+ const bucket = merged[kind] ??= [];
161
+ for (const value of values) bucket.push({
162
+ value,
163
+ source: {
164
+ pluginName: plugin.name,
165
+ provenance
166
+ }
167
+ });
168
+ }
169
+ return merged;
170
+ }
171
+ //#endregion
172
+ export { PluginError, entryActiveForVerb, hostTypeSatisfies, mergeContributions, normalizePluginEntries, normalizePluginEntry, pluginEntryObjectSchema, pluginEntrySchema, registerHostType, resolveOrder, runObserveHook, runObserveHookSequential, runProvideHook, runTransformHook };
173
+
174
+ //# sourceMappingURL=plugins.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugins.mjs","names":[],"sources":["../src/plugins.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/**\n * R1 — the host plugin framework (bridge-runners-to-plugins plan,\n * customization-references/host-core as the blueprint).\n *\n * A plugin is hooks + contributions; hooks are boot wiring (main realm only),\n * contributions are declarative, serializable surface. Host RUNTIMES define\n * the hook vocabulary and interleave their own wiring between stages — they\n * are never plugins themselves.\n *\n * host.js carries the COMPOSITION as `runner.plugins` entries:\n * string | { module, enabled?, verbs?, config? }\n * Presence is activation (enabled defaults true); `verbs` scopes an entry to\n * matching run verbs; `config` is validated against the plugin's declared\n * zod schema. Entries resolve from the PROJECT's dependency tree exactly\n * like runner modules.\n */\n\nexport class PluginError extends Error {\n constructor(message: string, hint?: string) {\n super(hint ? `${message}\\n Hint: ${hint}` : message);\n this.name = \"PluginError\";\n }\n}\n\n/* ------------------------------------------------------------------ entries */\n\nexport const pluginEntryObjectSchema = z.strictObject({\n module: z.string().min(1),\n /** Presence is activation BY DEFAULT; false is the explicit off-switch. */\n enabled: z.boolean().optional(),\n /** \"*\" (default) or the run verbs this entry is active for. */\n verbs: z\n .union([z.literal(\"*\"), z.array(z.string().min(1)).min(1)])\n .optional(),\n /** Validated against the plugin's declared configSchema at resolution. */\n config: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const pluginEntrySchema = z.union([\n z.string().min(1),\n pluginEntryObjectSchema,\n]);\n\nexport type PluginEntry = z.infer<typeof pluginEntrySchema>;\n\nexport interface NormalizedPluginEntry {\n module: string;\n enabled: boolean;\n verbs: \"*\" | string[];\n config: Record<string, unknown>;\n}\n\nexport function normalizePluginEntry(\n entry: PluginEntry,\n): NormalizedPluginEntry {\n if (typeof entry === \"string\") {\n return { module: entry, enabled: true, verbs: \"*\", config: {} };\n }\n return {\n module: entry.module,\n enabled: entry.enabled ?? true,\n verbs: entry.verbs ?? \"*\",\n config: entry.config ?? {},\n };\n}\n\n/** Module is the identity key: a duplicate makes override targeting and\n * ordering ambiguous, so it fails loudly. */\nexport function normalizePluginEntries(\n entries: readonly PluginEntry[],\n where: string,\n): NormalizedPluginEntry[] {\n const normalized = entries.map(normalizePluginEntry);\n const seen = new Set<string>();\n for (const entry of normalized) {\n if (seen.has(entry.module)) {\n throw new PluginError(\n `${where}: plugin \"${entry.module}\" is listed twice.`,\n \"Module specifiers are the identity key of a composition; a plugin meant to run twice needs distinct subpath specifiers.\",\n );\n }\n seen.add(entry.module);\n }\n return normalized;\n}\n\nexport function entryActiveForVerb(\n entry: NormalizedPluginEntry,\n verb: string,\n): boolean {\n if (!entry.enabled) return false;\n return entry.verbs === \"*\" || entry.verbs.includes(verb);\n}\n\n/* ---------------------------------------------------------------- hierarchy */\n\n/**\n * The appliesTo hierarchy. \"reactor\" is the base every reactor host extends;\n * \"compound\" is its own branch (plugins over the member set — e.g. the clint\n * proxy). Host runtimes register their id with a parent; compatibility walks\n * the parent chain.\n */\nconst HOST_TYPE_PARENTS: Record<string, string | null> = {\n reactor: null,\n compound: null,\n connect: \"reactor\",\n switchboard: \"reactor\",\n mastra: \"reactor\",\n};\n\nexport function registerHostType(id: string, parent: string | null): void {\n if (id in HOST_TYPE_PARENTS && HOST_TYPE_PARENTS[id] !== parent) {\n throw new PluginError(\n `Host type \"${id}\" is already registered with parent \"${String(HOST_TYPE_PARENTS[id])}\".`,\n );\n }\n HOST_TYPE_PARENTS[id] = parent;\n}\n\nexport function hostTypeSatisfies(\n hostType: string,\n appliesTo: string,\n): boolean {\n let current: string | null = hostType;\n while (current !== null) {\n if (current === appliesTo) return true;\n current = current in HOST_TYPE_PARENTS ? HOST_TYPE_PARENTS[current] : null;\n }\n return false;\n}\n\n/* ------------------------------------------------------------------- plugin */\n\n/** Hook kinds (v1 §2.2). The hook VOCABULARY is defined by host runtimes;\n * plugins implement subsets of it. */\nexport type Provide<T, C> = (ctx: C) => T | Promise<T>;\nexport type Transform<T, C> = (value: T, ctx: C) => T | Promise<T>;\nexport type Observe<C> = (ctx: C) => void | Promise<void>;\n\n/**\n * Core contributions — declarative, serializable, realm-crossing. Host\n * runtimes extend this with their own kinds (UI slots live in connect-host,\n * never here). `drives` entries use the drive declaration shape from\n * drives.ts; kept as unknown here to avoid a cycle — the merge is shape-blind.\n */\nexport interface Contributions {\n drives?: unknown[];\n packages?: string[];\n configDeclarations?: { name: string; type?: string; description?: string }[];\n [kind: string]: unknown[] | undefined;\n}\n\nexport interface HostPlugin<\n THooks = Record<string, unknown>,\n TConfig = unknown,\n> {\n /** Stable id; used in ordering, dependsOn, and every diagnostic. */\n name: string;\n /** Host-type requirement; the entry is rejected on a host outside the\n * hierarchy branch. Default: \"reactor\". */\n appliesTo?: string;\n /** Coarse ordering bucket (Vite-style). Default: \"normal\". */\n enforce?: \"pre\" | \"post\";\n /** Hard dependencies on OTHER PLUGINS — the host runtime is implied and\n * never named. Missing dependency or cycle fails boot naming both sides. */\n dependsOn?: string[];\n /** Declared config shape; entry config is validated against it. A plugin\n * without a schema accepts no config (passing one is a boot error). */\n configSchema?: z.ZodType<TConfig>;\n hooks?: Partial<THooks>;\n contributions?: Contributions;\n}\n\n/** A plugin module default-exports either a HostPlugin object (no config\n * accepted) or a factory `(config) => HostPlugin`. */\nexport type HostPluginModule<\n THooks = Record<string, unknown>,\n TConfig = unknown,\n> =\n | HostPlugin<THooks, TConfig>\n | ((config: TConfig) => HostPlugin<THooks, TConfig>);\n\nexport interface ResolvedPlugin<THooks = Record<string, unknown>> {\n entry: NormalizedPluginEntry;\n plugin: HostPlugin<THooks>;\n /** Provenance for contribution merge ordering. */\n provenance: \"built-in\" | \"local\" | \"dependency\";\n}\n\n/* ----------------------------------------------------------------- ordering */\n\n/** Registration order, bucketed pre → normal → post (stable within buckets),\n * then dependsOn topo-sorted within the bucketed order. */\nexport function resolveOrder<THooks>(\n plugins: readonly HostPlugin<THooks>[],\n): HostPlugin<THooks>[] {\n const buckets: Record<\"pre\" | \"normal\" | \"post\", HostPlugin<THooks>[]> = {\n pre: [],\n normal: [],\n post: [],\n };\n for (const plugin of plugins)\n buckets[plugin.enforce ?? \"normal\"].push(plugin);\n const bucketed = [...buckets.pre, ...buckets.normal, ...buckets.post];\n\n const byName = new Map(bucketed.map((p) => [p.name, p]));\n for (const plugin of bucketed) {\n for (const dep of plugin.dependsOn ?? []) {\n if (!byName.has(dep)) {\n throw new PluginError(\n `Plugin \"${plugin.name}\" depends on missing plugin \"${dep}\".`,\n \"dependsOn names PLUGINS only — the host runtime is implied and never named.\",\n );\n }\n }\n }\n\n const ordered: HostPlugin<THooks>[] = [];\n const state = new Map<string, \"visiting\" | \"done\">();\n const visit = (plugin: HostPlugin<THooks>, chain: string[]): void => {\n const mark = state.get(plugin.name);\n if (mark === \"done\") return;\n if (mark === \"visiting\") {\n throw new PluginError(\n `Plugin dependency cycle: ${[...chain, plugin.name].join(\" -> \")}.`,\n );\n }\n state.set(plugin.name, \"visiting\");\n for (const dep of plugin.dependsOn ?? []) {\n visit(byName.get(dep)!, [...chain, plugin.name]);\n }\n state.set(plugin.name, \"done\");\n ordered.push(plugin);\n };\n for (const plugin of bucketed) visit(plugin, []);\n return ordered;\n}\n\n/* -------------------------------------------------------------------- hooks */\n\nexport async function runProvideHook<T, C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n): Promise<T | undefined> {\n const impls = plugins.filter((p) => typeof p.hooks?.[name] === \"function\");\n if (impls.length > 1) {\n throw new PluginError(\n `Hook \"${name}\" is provided by ${impls.map((p) => `\"${p.name}\"`).join(\" and \")} — provide hooks have one winner.`,\n );\n }\n const impl = impls[0]?.hooks?.[name] as Provide<T, C> | undefined;\n return impl ? await impl(ctx) : undefined;\n}\n\nexport async function runTransformHook<T, C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n seed: T,\n): Promise<T> {\n let value = seed;\n for (const plugin of plugins) {\n const impl = plugin.hooks?.[name] as Transform<T, C> | undefined;\n if (typeof impl === \"function\") value = await impl(value, ctx);\n }\n return value;\n}\n\n/** Sequential observe, in plugin order — for lifecycle moments whose order\n * is load-bearing (teardown: the switchboard stops privacy before workflows\n * before the api, per the carve map). */\nexport async function runObserveHookSequential<C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n): Promise<void> {\n for (const plugin of plugins) {\n const impl = plugin.hooks?.[name] as Observe<C> | undefined;\n if (typeof impl === \"function\") await impl(ctx);\n }\n}\n\nexport async function runObserveHook<C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n): Promise<void> {\n await Promise.all(\n plugins.map(async (plugin) => {\n const impl = plugin.hooks?.[name] as Observe<C> | undefined;\n if (typeof impl === \"function\") await impl(ctx);\n }),\n );\n}\n\n/* ------------------------------------------------------------ contributions */\n\nexport interface ContributionSource {\n pluginName: string;\n provenance: \"built-in\" | \"local\" | \"dependency\";\n}\n\nexport interface MergedContribution<T = unknown> {\n value: T;\n source: ContributionSource;\n}\n\n/** Array kinds concatenate in provenance-then-order sequence (built-in first,\n * so later sources read as overrides where consumers want last-wins). */\nexport function mergeContributions(\n resolved: readonly {\n plugin: HostPlugin;\n provenance: ContributionSource[\"provenance\"];\n }[],\n): Record<string, MergedContribution[]> {\n const rank: Record<ContributionSource[\"provenance\"], number> = {\n \"built-in\": 0,\n local: 1,\n dependency: 2,\n };\n const sorted = [...resolved].sort(\n (a, b) => rank[a.provenance] - rank[b.provenance],\n );\n const merged: Record<string, MergedContribution[]> = {};\n for (const { plugin, provenance } of sorted) {\n for (const [kind, values] of Object.entries(plugin.contributions ?? {})) {\n if (!values) continue;\n const bucket = (merged[kind] ??= []);\n for (const value of values) {\n bucket.push({ value, source: { pluginName: plugin.name, provenance } });\n }\n }\n }\n return merged;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,IAAa,cAAb,cAAiC,MAAM;CACrC,YAAY,SAAiB,MAAe;EAC1C,MAAM,OAAO,GAAG,QAAQ,YAAY,SAAS,OAAO;EACpD,KAAK,OAAO;CACd;AACF;AAIA,MAAa,0BAA0B,EAAE,aAAa;CACpD,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;;CAExB,SAAS,EAAE,QAAQ,CAAC,CAAC,SAAS;;CAE9B,OAAO,EACJ,MAAM,CAAC,EAAE,QAAQ,GAAG,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAC1D,SAAS;;CAEZ,QAAQ,EAAE,OAAO,EAAE,OAAO,GAAG,EAA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O;IAAM;GAAW;EAAE,CAAC;CAE1E;CAEF,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- import { c as RunnerContext, g as HostDefinition, i as RunCompoundResult } from "../compound-9--OujO-.mjs";
1
+ import { c as RunnerContext, g as HostDefinition, i as RunCompoundResult } from "../compound-C8P0kvPJ.mjs";
2
2
  //#region src/runners/compound.d.ts
3
3
  /**
4
4
  * The GENERIC compound runner module (phase 3): supervises the members a
@@ -19,10 +19,16 @@ export declare const hostSchema: import("zod").ZodObject<{
19
19
  module: import("zod").ZodString;
20
20
  defaultVerb: import("zod").ZodOptional<import("zod").ZodString>;
21
21
  port: import("zod").ZodOptional<import("zod").ZodNumber>;
22
+ host: import("zod").ZodOptional<import("zod").ZodString>;
23
+ plugins: import("zod").ZodOptional<import("zod").ZodArray<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodObject<{
24
+ module: import("zod").ZodString;
25
+ enabled: import("zod").ZodOptional<import("zod").ZodBoolean>;
26
+ verbs: import("zod").ZodOptional<import("zod").ZodUnion<readonly [import("zod").ZodLiteral<"*">, import("zod").ZodArray<import("zod").ZodString>]>>;
27
+ config: import("zod").ZodOptional<import("zod").ZodRecord<import("zod").ZodString, import("zod").ZodUnknown>>;
28
+ }, import("zod/v4/core").$strict>]>>>;
22
29
  }, import("zod/v4/core").$loose>;
23
30
  children: import("zod").ZodRecord<import("zod").ZodString, import("zod").ZodObject<{
24
31
  host: import("zod").ZodString;
25
- plugins: import("zod").ZodOptional<import("zod").ZodArray<import("zod").ZodString>>;
26
32
  runner: import("zod").ZodOptional<import("zod").ZodObject<{}, import("zod/v4/core").$loose>>;
27
33
  config: import("zod").ZodOptional<import("zod").ZodObject<{}, import("zod/v4/core").$loose>>;
28
34
  reactor: import("zod").ZodOptional<import("zod").ZodObject<{
@@ -54,12 +60,18 @@ export declare const hostSchema: import("zod").ZodObject<{
54
60
  host: import("zod").ZodOptional<import("zod").ZodString>;
55
61
  url: import("zod").ZodOptional<import("zod").ZodString>;
56
62
  }, import("zod/v4/core").$strict>>;
63
+ projection: import("zod").ZodOptional<import("zod").ZodObject<{
64
+ enabled: import("zod").ZodOptional<import("zod").ZodBoolean>;
65
+ dbPoolSize: import("zod").ZodOptional<import("zod").ZodNumber>;
66
+ }, import("zod/v4/core").$strict>>;
67
+ executors: import("zod").ZodOptional<import("zod").ZodObject<{
68
+ numWorkers: import("zod").ZodOptional<import("zod").ZodUnion<readonly [import("zod").ZodNumber, import("zod").ZodLiteral<"auto">]>>;
69
+ }, import("zod/v4/core").$strict>>;
57
70
  }, import("zod/v4/core").$strict>>>;
58
71
  placement: import("zod").ZodOptional<import("zod").ZodObject<{
59
72
  primary: import("zod").ZodOptional<import("zod").ZodString>;
60
73
  default: import("zod").ZodOptional<import("zod").ZodObject<{}, import("zod/v4/core").$loose>>;
61
74
  }, import("zod/v4/core").$strict>>;
62
- workflows: import("zod").ZodOptional<import("zod").ZodBoolean>;
63
75
  protocol: import("zod").ZodOptional<import("zod").ZodObject<{
64
76
  featureFlags: import("zod").ZodOptional<import("zod").ZodObject<{
65
77
  documentDecisions: import("zod").ZodOptional<import("zod").ZodBoolean>;
@@ -76,6 +88,38 @@ export declare const hostSchema: import("zod").ZodObject<{
76
88
  refuse: "refuse";
77
89
  }>>;
78
90
  }, import("zod/v4/core").$strict>>;
91
+ workflows: import("zod").ZodOptional<import("zod").ZodBoolean>;
92
+ renown: import("zod").ZodOptional<import("zod").ZodObject<{
93
+ url: import("zod").ZodOptional<import("zod").ZodString>;
94
+ networkId: import("zod").ZodOptional<import("zod").ZodString>;
95
+ chainId: import("zod").ZodOptional<import("zod").ZodNumber>;
96
+ }, import("zod/v4/core").$strict>>;
97
+ packages: import("zod").ZodOptional<import("zod").ZodObject<{
98
+ registryUrl: import("zod").ZodOptional<import("zod").ZodString>;
99
+ }, import("zod/v4/core").$strict>>;
100
+ namespace: import("zod").ZodOptional<import("zod").ZodString>;
101
+ auth: import("zod").ZodOptional<import("zod").ZodObject<{
102
+ enabled: import("zod").ZodOptional<import("zod").ZodBoolean>;
103
+ admins: import("zod").ZodOptional<import("zod").ZodArray<import("zod").ZodString>>;
104
+ renown: import("zod").ZodOptional<import("zod").ZodObject<{}, import("zod/v4/core").$loose>>;
105
+ }, import("zod/v4/core").$strict>>;
106
+ drives: import("zod").ZodOptional<import("zod").ZodArray<import("zod").ZodObject<{
107
+ slug: import("zod").ZodString;
108
+ id: import("zod").ZodOptional<import("zod").ZodString>;
109
+ projectHash: import("zod").ZodOptional<import("zod").ZodBoolean>;
110
+ name: import("zod").ZodOptional<import("zod").ZodString>;
111
+ icon: import("zod").ZodOptional<import("zod").ZodString>;
112
+ preferredEditor: import("zod").ZodOptional<import("zod").ZodString>;
113
+ sharingType: import("zod").ZodOptional<import("zod").ZodEnum<{
114
+ private: "private";
115
+ public: "public";
116
+ shared: "shared";
117
+ }>>;
118
+ availableOffline: import("zod").ZodOptional<import("zod").ZodBoolean>;
119
+ remote: import("zod").ZodOptional<import("zod").ZodObject<{
120
+ url: import("zod").ZodString;
121
+ }, import("zod/v4/core").$strict>>;
122
+ }, import("zod/v4/core").$strict>>>;
79
123
  }, import("zod/v4/core").$strict>>;
80
124
  }, import("zod/v4/core").$strict>>;
81
125
  config: import("zod").ZodOptional<import("zod").ZodObject<{}, import("zod/v4/core").$loose>>;
@@ -1 +1 @@
1
- {"version":3,"file":"compound.d.mts","names":[],"sources":["../../src/runners/compound.ts"],"mappings":";;;;;;;;;;;;;;qBAoBa;qBAEA,0BAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;yBAAqB;wBA0BtB,IACpB,MAAM,gBACN,KAAK,gBACJ,QAAQ;wBAKW,IACpB,MAAM,gBACN,KAAK,gBACJ,QAAQ;wBAIW,MACpB,MAAM,gBACN,KAAK,gBACJ,QAAQ;wBAIW,MACpB,MAAM,gBACN,KAAK,gBACJ,QAAQ"}
1
+ {"version":3,"file":"compound.d.mts","names":[],"sources":["../../src/runners/compound.ts"],"mappings":";;;;;;;;;;;;;;qBAoBa;qBAEA,0BAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;yBAAqB;wBA0BtB,IACpB,MAAM,gBACN,KAAK,gBACJ,QAAQ;wBAKW,IACpB,MAAM,gBACN,KAAK,gBACJ,QAAQ;wBAIW,MACpB,MAAM,gBACN,KAAK,gBACJ,QAAQ;wBAIW,MACpB,MAAM,gBACN,KAAK,gBACJ,QAAQ"}
@@ -1,4 +1,4 @@
1
- import { n as compoundHostSchema, u as runCompound } from "../host-schemas-C_MLcYX6.mjs";
1
+ import { _ as runCompound, n as compoundHostSchema } from "../host-schemas-CL_wFpY7.mjs";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  //#region src/runners/compound.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerhousedao/host-core",
3
- "version": "6.2.3-dev.57",
3
+ "version": "6.2.3-dev.59",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -28,16 +28,22 @@
28
28
  "types": "./dist/runners/compound.d.mts",
29
29
  "import": "./dist/runners/compound.mjs",
30
30
  "default": "./dist/runners/compound.mjs"
31
+ },
32
+ "./plugins": {
33
+ "source": "./src/plugins.ts",
34
+ "types": "./dist/plugins.d.mts",
35
+ "import": "./dist/plugins.mjs",
36
+ "default": "./dist/plugins.mjs"
31
37
  }
32
38
  },
33
39
  "dependencies": {
34
- "@powerhousedao/shared": "6.2.3-dev.57",
40
+ "@powerhousedao/shared": "6.2.3-dev.59",
35
41
  "zod": "4.3.6"
36
42
  },
37
43
  "devDependencies": {
38
44
  "tsdown": "0.23.0",
39
45
  "vitest": "5.0.3",
40
- "@powerhousedao/reactor-monitor": "6.2.3-dev.57"
46
+ "@powerhousedao/reactor-monitor": "6.2.3-dev.59"
41
47
  },
42
48
  "scripts": {
43
49
  "tsc": "tsc",
@@ -1 +0,0 @@
1
- {"version":3,"file":"compound-9--OujO-.d.mts","names":[],"sources":["../src/host-loader.ts","../src/runner-resolver.ts","../src/compound.ts"],"mappings":";cAuBa,sBAAsB;EACjC,YAAY,iBAAiB;;KAMnB;EACN;;EACA;EAAe;;EACf;EAAiB;EAAa;;;;;iBAKpB,iBAAiB,sBAAsB;;;;iBAqBvC,gBAAgB,gBAAgB;;;iBA0BhC,mBACd,gBACA;UA4Be;EACf;EACA;IAAU;MAAmB;EAC7B,SAAS;EACT,UAAU;EACV,UAAU;EACV,WAAW;;UAGI;EACf;EACA;EACA;EACA,MAAM;;iBA2Bc,SACpB,qBACA,mBACC,QAAQ;;;;;;;;;;cCjJE,oBAAoB;EAC/B,YAAY,iBAAiB;;UAMd;EACf;EACA;EACA,KAAK;;KAGK,cACV,MAAM,gBACN,KAAK,kBACF;;UAGY;EACf,UAAU;IACR;IACA;MAAU;QAAW;QAA2B;;;;;UAInC;EACf,KAAK;EACL,YAAY;EACZ;GACC;;iBAMmB,oBACpB,qBACA,oBACC,QAAQ;iBAsCK,UAAU,QAAQ;iBAUlB,QACd,QAAQ,cACR,mBACA,eACC;iBAYa,aACd,QAAQ,cACR,mBACA,MAAM,gBACN;;;;;;;;;;;;;;;;;UCrFe;;EAEf;;;EAGA;;EAEA,YAAY;;;EAGZ,QAAQ;;EAER,wBAAwB;;UAGT;EACf;EACA;EACA;IAAW;MAAkB;EAC7B,SAAS;EACT,UAAU;;UAGK;;EAEf;;EAEA;;EAEA;;EAEA;;;EAGA;;UAGQ;EACR;EACA,QAAQ;;UA+DO;;EAEf;;EAEA,cAAc;;EAEd;;UAGe;EACf,SAAS;EACT,gBAAgB;;iBAGI,YACpB,MAAM,gBACN,KAAK,eACL,SAAS,qBACR,QAAQ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"host-schemas-C_MLcYX6.mjs","names":[],"sources":["../src/connect-projection.ts","../src/host-loader.ts","../src/runner-resolver.ts","../src/run-record.ts","../src/placeholders.ts","../src/compound.ts","../src/host-schemas.ts"],"sourcesContent":["import type {\n PHConnectDefaultDrive,\n PHConnectRuntimeConfig,\n} from \"@powerhousedao/shared/clis\";\n\n/**\n * Instance-fact projection for compound hosts: the drives a compound's\n * reactor member created, projected into the Connect member's runtime-config\n * override. Pure functions, moved from ph-cli's vetra service so the generic\n * compound and the classic path share one implementation.\n */\n\nfunction isLocalDrive(\n drive: PHConnectDefaultDrive,\n): drive is Extract<PHConnectDefaultDrive, { local: true }> {\n return \"local\" in drive;\n}\n\n// Identity key for de-duplication: remote entries are keyed by URL; local\n// entries are keyed by `local:<id>` so a local drive id can never collide\n// with a remote URL that happens to be the same string.\nconst driveKey = (drive: PHConnectDefaultDrive): string =>\n isLocalDrive(drive) ? `local:${drive.id}` : drive.url;\n\n/**\n * Concatenate groups of `connect.drives.defaultDrives` in the order given,\n * de-duplicating by drive identity (URL for remote entries, id for local\n * ones). The first occurrence of a drive wins, so earlier groups keep their\n * position and metadata — e.g. the Vetra drive `ph vetra` starts stays first\n * even when the project's `powerhouse.config.json` lists the same drive.\n */\nexport function mergeDefaultDrives(\n ...groups: PHConnectDefaultDrive[][]\n): PHConnectDefaultDrive[] {\n const seen = new Set<string>();\n const out: PHConnectDefaultDrive[] = [];\n for (const group of groups) {\n for (const drive of group) {\n const key = driveKey(drive);\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(drive);\n }\n }\n return out;\n}\n\n/**\n * Rebase a local drive URL onto a public base: keeps the /d/<slug> path,\n * swaps the loopback origin for the public base. Browser clients behind a\n * reverse proxy can't reach http://localhost:<port>. Non-loopback URLs\n * (e.g. a remote drive) are already public and pass through unchanged, as do\n * unparseable ones.\n */\nexport function rebaseDriveUrl(driveUrl: string, publicBase: string): string {\n let url: URL;\n try {\n url = new URL(driveUrl);\n } catch {\n return driveUrl;\n }\n if (![\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname)) {\n return driveUrl;\n }\n return `${publicBase.replace(/\\/+$/, \"\")}${url.pathname}`;\n}\n\nexport interface DriveProjectionInput {\n /** Drive URLs the compound's reactor member created, in display order\n * (e.g. vetra, preview, workflows). Null/undefined entries are skipped. */\n createdDriveUrls: (string | null | undefined)[];\n /** The project's configured `connect.drives.defaultDrives`. */\n configuredDefaultDrives?: PHConnectDefaultDrive[];\n /** `--drives-public-base`: advertise proxy-reachable URLs to the browser. */\n publicBase?: string | null;\n}\n\n/**\n * The compound's drives projection: created drives first (rebased onto the\n * public base when given), then the project's configured drives, de-duplicated\n * — and `preserve-all`, because compound-injected drive lists change per\n * launch context and must never detach drives the user added by hand.\n */\nexport function projectDrivesIntoConnect(\n input: DriveProjectionInput,\n): Pick<PHConnectRuntimeConfig, \"drives\"> {\n const created: PHConnectDefaultDrive[] = input.createdDriveUrls\n .filter((url): url is string => typeof url === \"string\" && url.length > 0)\n .map((url) => ({\n url: input.publicBase ? rebaseDriveUrl(url, input.publicBase) : url,\n name: null,\n icon: null,\n }));\n return {\n drives: {\n defaultDrives: mergeDefaultDrives(\n created,\n input.configuredDefaultDrives ?? [],\n ),\n preserveStrategy: \"preserve-all\",\n },\n };\n}\n","import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\n/**\n * Loads and pre-validates a `hosts/<name>/host.js` definition.\n *\n * A host file is a static PROJECTION of powerhouse.config.json: plain ESM,\n * default-exporting a data object. Three gates run before any runner sees it:\n * 1. import lint — the only legal import is the project's\n * powerhouse.config.json (host files are data, not programs);\n * 2. static check — the exported object must survive a JSON round trip\n * (functions, undefined, class instances, Dates etc. are rejected,\n * reporting the offending path);\n * 3. shape pre-check — `name`, `runner.module`, and the reactor XOR children\n * rule. Full validation is the runner's `hostSchema` (phase 2).\n *\n * This module never exits the process — callers own error presentation.\n */\n\nconst HOST_FILE = \"host.js\";\nconst CONFIG_IMPORT_SUFFIX = \"powerhouse.config.json\";\n\nexport class HostLoadError extends Error {\n constructor(message: string, hint?: string) {\n super(hint ? `${message}\\n Hint: ${hint}` : message);\n this.name = \"HostLoadError\";\n }\n}\n\nexport type HostsFolderStatus =\n | { kind: \"absent\" }\n | { kind: \"empty\"; dir: string }\n | { kind: \"present\"; dir: string; hosts: string[] };\n\n/** A `hosts/` folder with no `<name>/host.js` inside is \"empty\" — the guard\n * state: callers warn loudly and fall back to legacy rather than activating\n * the new architecture off a stray `mkdir hosts`. */\nexport function probeHostsFolder(projectRoot: string): HostsFolderStatus {\n const dir = path.join(projectRoot, \"hosts\");\n if (!existsSync(dir) || !statSync(dir).isDirectory()) {\n return { kind: \"absent\" };\n }\n const hosts = readdirSync(dir, { withFileTypes: true })\n .filter(\n (entry) =>\n entry.isDirectory() &&\n existsSync(path.join(dir, entry.name, HOST_FILE)),\n )\n .map((entry) => entry.name)\n .sort();\n return hosts.length === 0\n ? { kind: \"empty\", dir }\n : { kind: \"present\", dir, hosts };\n}\n\n/** Rejects every import except the project's powerhouse.config.json, plus any\n * dynamic `import(...)` or `require(...)`. Source-level enforcement: the JSON\n * round trip below is the hard gate; this one produces the better error. */\nexport function lintHostImports(source: string, file: string): void {\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)) {\n throw new HostLoadError(\n `${file} imports \"${specifier}\" — a host file may only import the project's powerhouse.config.json.`,\n \"Host files are static projections; code belongs in plugins.js or the runner.\",\n );\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.`,\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}\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 interface HostDefinition {\n name: string;\n runner: { module: string } & Record<string, unknown>;\n config?: Record<string, unknown>;\n profile?: Record<string, unknown>;\n reactor?: Record<string, unknown>;\n children?: Record<string, unknown>;\n}\n\nexport interface LoadedHost {\n name: string;\n dir: string;\n file: string;\n host: HostDefinition;\n}\n\nfunction assertHostShape(\n host: Record<string, unknown>,\n file: string,\n): asserts host is HostDefinition & Record<string, unknown> {\n if (typeof host.name !== \"string\" || host.name.length === 0) {\n throw new HostLoadError(`${file}: \\`name\\` must be a non-empty string.`);\n }\n const runner = host.runner;\n if (\n runner === null ||\n typeof runner !== \"object\" ||\n typeof (runner as Record<string, unknown>).module !== \"string\"\n ) {\n throw new HostLoadError(\n `${file}: \\`runner\\` must be an object with a \\`module\\` specifier string.`,\n );\n }\n if (host.reactor !== undefined && host.children !== undefined) {\n throw new HostLoadError(\n `${file}: \\`reactor\\` and \\`children\\` are mutually exclusive — a host is a reactor runner or a compound runner, never both.`,\n );\n }\n}\n\nexport async function loadHost(\n projectRoot: string,\n hostName: string,\n): Promise<LoadedHost> {\n const probe = probeHostsFolder(projectRoot);\n if (probe.kind === \"absent\") {\n throw new HostLoadError(\n `No hosts/ folder found in ${projectRoot}.`,\n \"Scaffold one with `ph init --uniform-runners` (or create hosts/<name>/host.js).\",\n );\n }\n if (probe.kind === \"empty\") {\n throw new HostLoadError(\n `hosts/ exists at ${probe.dir} but contains no <name>/host.js.`,\n \"An empty hosts/ folder does not activate the uniform-runners architecture; add a host definition or remove the folder.\",\n );\n }\n if (!probe.hosts.includes(hostName)) {\n throw new HostLoadError(\n `Unknown host \"${hostName}\". Available hosts: ${probe.hosts.join(\", \")}.`,\n );\n }\n\n const file = path.join(probe.dir, hostName, HOST_FILE);\n lintHostImports(readFileSync(file, \"utf8\"), file);\n\n const module = (await import(pathToFileURL(file).href)) as {\n default?: unknown;\n };\n const host = module.default;\n if (host === null || typeof host !== \"object\" || Array.isArray(host)) {\n throw new HostLoadError(\n `${file} must default-export the host object (\\`export default { name, runner, ... }\\`).`,\n );\n }\n\n const nonStatic = findNonStaticValue(host);\n if (nonStatic) {\n throw new HostLoadError(\n `${file} exports a non-static value at \\`${nonStatic}\\` — host files must survive a JSON round trip.`,\n \"Runtime behavior belongs in the runner; host files only carry data.\",\n );\n }\n\n assertHostShape(host as Record<string, unknown>, file);\n return {\n name: hostName,\n dir: path.dirname(file),\n file,\n host: host as HostDefinition,\n };\n}\n","import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { HostDefinition } from \"./host-loader.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, ...optionalVerbs }`. Phase-0 home is ph-cli; the\n * uniform-runners plan moves this into @powerhousedao/host-core with the\n * generic compound (phase 1).\n */\n\nexport class RunnerError extends Error {\n constructor(message: string, hint?: string) {\n super(hint ? `${message}\\n Hint: ${hint}` : message);\n this.name = \"RunnerError\";\n }\n}\n\nexport interface RunnerContext {\n projectRoot: string;\n verb: string;\n env: Record<string, string | undefined>;\n}\n\nexport type RunnerVerb = (\n host: HostDefinition,\n ctx: RunnerContext,\n) => Promise<unknown>;\n\n/** zod-shaped structurally, so this module needs no zod dependency. */\nexport interface HostSchemaLike {\n safeParse(host: unknown): {\n success: boolean;\n error?: { issues?: { path: (string | number)[]; message: string }[] };\n };\n}\n\nexport interface RunnerModule {\n run: RunnerVerb;\n hostSchema: HostSchemaLike;\n kind: string;\n [key: string]: unknown;\n}\n\n/** Exports that are part of the contract but are not verbs. */\nconst NON_VERB_EXPORTS = new Set([\"hostSchema\", \"kind\", \"default\"]);\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 let resolved: string;\n try {\n resolved = projectRequire.resolve(specifier);\n } catch {\n throw new RunnerError(\n `Cannot resolve runner module \"${specifier}\" from ${projectRoot}.`,\n \"The runner must be a dependency of the project (install it, then retry).\",\n );\n }\n\n const module = (await import(pathToFileURL(resolved).href)) as Record<\n string,\n unknown\n >;\n\n if (typeof module.run !== \"function\") {\n throw new RunnerError(\n `Runner \"${specifier}\" does not export a \\`run\\` function (required verb).`,\n );\n }\n const hostSchema = module.hostSchema as HostSchemaLike | undefined;\n if (!hostSchema || typeof hostSchema.safeParse !== \"function\") {\n throw new RunnerError(\n `Runner \"${specifier}\" does not export a \\`hostSchema\\` — runners validate their own host shape.`,\n );\n }\n if (typeof module.kind !== \"string\") {\n throw new RunnerError(\n `Runner \"${specifier}\" does not export \\`kind\\` (e.g. \"reactor\" | \"compound\").`,\n );\n }\n return module as unknown as RunnerModule;\n}\n\nexport function listVerbs(runner: RunnerModule): string[] {\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(\n runner: RunnerModule,\n specifier: string,\n verb: string,\n): RunnerVerb {\n const candidate = runner[verb];\n if (typeof candidate !== \"function\" || NON_VERB_EXPORTS.has(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;\n}\n\nexport function validateHost(\n runner: RunnerModule,\n specifier: string,\n host: HostDefinition,\n file: string,\n): void {\n const result = runner.hostSchema.safeParse(host);\n if (!result.success) {\n const issues = (result.error?.issues ?? [])\n .map(\n (issue) => ` - ${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n )\n .join(\"\\n\");\n throw new RunnerError(\n `${file} failed validation against the hostSchema of \"${specifier}\":\\n${issues || \" (no details reported)\"}`,\n );\n }\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * A running host's `.ph/run/<host>.json` record: what is live for this\n * project, keyed by host name so N hosts (vetra, desktop, …) coexist. This is\n * the generic form of ph-cli's vetra-runtime record; the compound writes one\n * per supervised host and (for compatibility) keeps the legacy\n * vetra-runtime.json in step while agent tooling still reads it (D1.c).\n */\nexport interface RunRecordMember {\n port?: number;\n url?: string;\n}\n\nexport interface RunRecord {\n pid: number;\n hostName: string;\n projectName: string;\n startedAt: string;\n members: Record<string, RunRecordMember>;\n /** Host-specific extras (e.g. mcpUrl) a runner wants in the record. */\n extra?: Record<string, unknown>;\n}\n\nexport type RunProbe =\n | { status: \"none\" }\n | { status: \"stale\"; record: RunRecord }\n | { status: \"live\"; record: RunRecord }\n | { status: \"foreign\"; record: RunRecord };\n\nconst runDir = (projectDir: string) => path.join(projectDir, \".ph\", \"run\");\nconst recordPath = (projectDir: string, hostName: string) =>\n path.join(runDir(projectDir), `${hostName}.json`);\n\nexport function readRunRecord(\n projectDir: string,\n hostName: string,\n): RunRecord | undefined {\n try {\n return JSON.parse(\n fs.readFileSync(recordPath(projectDir, hostName), \"utf8\"),\n ) as RunRecord;\n } catch {\n return undefined;\n }\n}\n\nexport function writeRunRecord(projectDir: string, record: RunRecord): void {\n const target = recordPath(projectDir, record.hostName);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, `${JSON.stringify(record, null, 2)}\\n`);\n}\n\nexport function clearRunRecord(projectDir: string, hostName: string): void {\n try {\n fs.rmSync(recordPath(projectDir, hostName));\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/**\n * Decide whether the recorded instance is this project's live host.\n *\n * pid liveness alone proves nothing (pids are reused), and 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 pid) is reported so the caller can clear it; a\n * foreign one (live pid, different project) is left alone.\n */\nexport function probeRun(\n projectDir: string,\n hostName: string,\n projectName: string,\n): RunProbe {\n const record = readRunRecord(projectDir, hostName);\n if (!record) return { status: \"none\" };\n if (!isPidAlive(record.pid)) return { status: \"stale\", record };\n if (record.projectName !== projectName) return { status: \"foreign\", record };\n return { status: \"live\", record };\n}\n","import path from \"node:path\";\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}/pglite` and the RUNNER resolves it at\n * start. In the CLI the default userData is `<projectRoot>/.ph/user-data`;\n * a shell (Tauri) overrides it via PH_USER_DATA_DIR to the OS profile dir.\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.join(projectRoot, \".ph\", \"user-data\");\n}\n\nconst PLACEHOLDER = /\\$\\{userData\\}/g;\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 if (typeof value === \"string\") {\n return value.replace(PLACEHOLDER, userData) as unknown as T;\n }\n if (Array.isArray(value)) {\n return value.map((v) =>\n resolveUserDataPlaceholders<unknown>(v, userData),\n ) as T;\n }\n if (value !== null && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n out[k] = resolveUserDataPlaceholders(v, userData);\n }\n return out as T;\n }\n return value;\n}\n","import type { HostDefinition } from \"./host-loader.js\";\nimport { loadHost } from \"./host-loader.js\";\nimport { projectDrivesIntoConnect } from \"./connect-projection.js\";\nimport {\n defaultUserDataDir,\n resolveUserDataPlaceholders,\n} from \"./placeholders.js\";\nimport {\n clearRunRecord,\n probeRun,\n writeRunRecord,\n type RunRecordMember,\n} from \"./run-record.js\";\nimport {\n getVerb,\n resolveRunnerModule,\n validateHost,\n type RunnerContext,\n} from \"./runner-resolver.js\";\n\n/**\n * The generic compound runner: supervises the members a compound host\n * declares, each started via its OWN declared runner at the compound's member\n * verb. It projects a reactor member's created drives into a connect member's\n * config, writes a .ph/run/<host>.json record, holds a per-project lock, and\n * tears members down in reverse order on shutdown.\n *\n * Phase-1 model is ATTACHED and in-process: member runner verbs start their\n * servers (which hold the event loop) and return a handle of facts; the\n * compound stays alive as long as they do. Detached supervision is phase 5.\n */\n\n/** Facts a member runner verb returns so the compound can project and tear\n * down. All optional: a void-returning verb is treated as \"started, no facts,\n * self-sustaining\" (the phase-0 bridges). */\nexport interface RunnerHandle {\n /** Port the member bound. */\n port?: number;\n /** Drive URLs a reactor member created, in display order — projected into a\n * connect member's defaultDrives. */\n driveUrls?: (string | null | undefined)[];\n /** Named endpoints (graphql, mcp, …) for the run record / diagnostics. */\n endpoints?: Record<string, string>;\n /** Resolves when the member is serving; the compound awaits it before the\n * next member when ordering requires readiness. */\n ready?: Promise<void>;\n /** Reverse-order teardown. */\n shutdown?: () => void | Promise<void>;\n}\n\nexport interface CompoundMember {\n host: string;\n plugins?: string[];\n runner?: { port?: number } & Record<string, unknown>;\n config?: Record<string, unknown>;\n reactor?: Record<string, unknown>;\n}\n\nexport interface CompoundWiring {\n /** Project the reactor member's created drives into the connect member. */\n projectDrivesIntoConnect?: boolean;\n /** --drives-public-base equivalent. */\n drivesPublicBase?: string | null;\n /** Member start order; defaults to declaration order. */\n startOrder?: string[];\n /** Write .ph/run/<host>.json (default true). */\n runtimeRecord?: boolean;\n /** Patch the baked CSP for the runtime registry on a served connect member\n * (forwarded to the connect runner as a runner option). */\n cspRegistrySync?: boolean;\n}\n\ninterface StartedMember {\n name: string;\n handle: RunnerHandle;\n}\n\nfunction memberEntries(host: HostDefinition): [string, CompoundMember][] {\n const children = (host.children ?? {}) as Record<string, CompoundMember>;\n return Object.entries(children);\n}\n\nfunction orderedMembers(\n host: HostDefinition,\n wiring: CompoundWiring,\n): [string, CompoundMember][] {\n const entries = memberEntries(host);\n if (!wiring.startOrder) return entries;\n const byName = new Map(entries);\n const out: [string, CompoundMember][] = [];\n for (const name of wiring.startOrder) {\n const m = byName.get(name);\n if (m) {\n out.push([name, m]);\n byName.delete(name);\n }\n }\n // any not named in startOrder keep declaration order, after the named ones\n for (const [name, m] of entries) if (byName.has(name)) out.push([name, m]);\n return out;\n}\n\n/** Build the member host object the member runner sees: the member's own\n * host.js, with the wrapper's runner/config/reactor overrides applied\n * (wrapper wins), and any compound-computed config patch merged in. */\nasync function resolveMemberHost(\n projectRoot: string,\n member: CompoundMember,\n userData: string,\n configPatch?: Record<string, unknown>,\n): Promise<HostDefinition> {\n const loaded = await loadHost(projectRoot, member.host);\n const base = loaded.host;\n const merged: HostDefinition = {\n ...base,\n runner: { ...base.runner, ...(member.runner ?? {}) },\n config: {\n ...(base.config ?? {}),\n ...(member.config ?? {}),\n ...(configPatch ?? {}),\n },\n reactor: { ...(base.reactor ?? {}), ...(member.reactor ?? {}) } as\n | Record<string, unknown>\n | undefined,\n };\n // ${userData} in the merged host (storage dirs etc.) resolves here — at the\n // runner, never derived from the instance name, so renames stay safe.\n return resolveUserDataPlaceholders(merged, userData);\n}\n\nfunction isConnectMember(member: CompoundMember): boolean {\n return member.host === \"connect\";\n}\nfunction isReactorFactMember(member: CompoundMember): boolean {\n return member.host === \"switchboard\";\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 signal handlers for teardown (default true; tests pass false). */\n installSignalHandlers?: boolean;\n}\n\nexport interface RunCompoundResult {\n started: StartedMember[];\n shutdown: () => Promise<void>;\n}\n\nexport async function runCompound(\n host: HostDefinition,\n ctx: RunnerContext,\n options: RunCompoundOptions,\n): Promise<RunCompoundResult> {\n const projectRoot = ctx.projectRoot;\n const wiring = (host.config ?? {}) as CompoundWiring;\n // The member verb is ctx.verb, resolved by the CALLING runner module (its\n // `run` maps to defaultVerb; its dev/build/serve forward themselves) — the\n // engine never consults defaultVerb, so an explicit verb always wins.\n const verb = ctx.verb;\n\n // Lock: one live instance per project per host (storage-root contention).\n const probe = probeRun(projectRoot, host.name, options.projectName);\n if (probe.status === \"live\") {\n throw new Error(\n `${host.name} is already running for this project (pid ${probe.record.pid}). ` +\n `Stop it before starting another.`,\n );\n }\n if (probe.status === \"foreign\") {\n throw new Error(\n `.ph/run/${host.name}.json describes a live \"${probe.record.projectName}\", ` +\n `but this project is \"${options.projectName}\". Refusing to start a second instance.`,\n );\n }\n // stale record: proceed (a dead pid does not hold the lock)\n\n const userData = defaultUserDataDir(projectRoot, ctx.env);\n const started: StartedMember[] = [];\n const reactorFacts: { driveUrls: (string | null | undefined)[] } = {\n driveUrls: [],\n };\n\n const shutdown = async () => {\n for (const m of [...started].reverse()) {\n try {\n await m.handle.shutdown?.();\n } catch {\n // best effort — keep tearing down the rest\n }\n }\n if (wiring.runtimeRecord !== false) {\n clearRunRecord(projectRoot, host.name);\n }\n };\n\n for (const [name, member] of orderedMembers(host, wiring)) {\n // Compute a config patch for the connect member from reactor facts.\n let configPatch: Record<string, unknown> | undefined;\n if (\n isConnectMember(member) &&\n wiring.projectDrivesIntoConnect &&\n reactorFacts.driveUrls.length > 0\n ) {\n const configuredDefaultDrives = (\n (member.config as { drives?: { defaultDrives?: unknown } } | undefined)\n ?.drives as { defaultDrives?: unknown } | undefined\n )?.defaultDrives as never;\n configPatch = projectDrivesIntoConnect({\n createdDriveUrls: reactorFacts.driveUrls,\n configuredDefaultDrives,\n publicBase: wiring.drivesPublicBase,\n });\n }\n\n const memberHost = await resolveMemberHost(\n projectRoot,\n member,\n userData,\n configPatch,\n );\n if (isConnectMember(member) && wiring.cspRegistrySync) {\n memberHost.runner = { ...memberHost.runner, cspRegistrySync: true };\n }\n const specifier = memberHost.runner.module;\n const runner = await resolveRunnerModule(projectRoot, specifier);\n validateHost(runner, specifier, memberHost, `hosts/${member.host}/host.js`);\n // At compound verb \"run\", each member runs its own (merged) defaultVerb —\n // \"each member's default mode\" — which is what lets a desktop compound\n // pair a switchboard at `run` with a connect at `serve`. An explicit\n // forwarded verb (dev/build/serve) stays uniform across members.\n const memberVerb =\n verb === \"run\"\n ? ((memberHost.runner.defaultVerb as string | undefined) ?? \"run\")\n : verb;\n const fn = getVerb(runner, specifier, memberVerb);\n const handle = ((await fn(memberHost, ctx)) ?? {}) as RunnerHandle;\n if (handle.ready) await handle.ready;\n started.push({ name, handle });\n\n if (isReactorFactMember(member) && handle.driveUrls) {\n reactorFacts.driveUrls.push(...handle.driveUrls);\n }\n }\n\n if (wiring.runtimeRecord !== false) {\n const members: Record<string, RunRecordMember> = {};\n for (const m of started) {\n members[m.name] = {\n port: m.handle.port,\n url: m.handle.endpoints?.graphql ?? m.handle.endpoints?.connect,\n };\n }\n writeRunRecord(projectRoot, {\n pid: process.pid,\n hostName: host.name,\n projectName: options.projectName,\n startedAt: new Date().toISOString(),\n members,\n extra: options.recordExtra,\n });\n }\n\n if (options.installSignalHandlers !== false) {\n const onSignal = (code: number) => {\n void shutdown().finally(() => process.exit(code));\n };\n process.on(\"exit\", () => {\n if (wiring.runtimeRecord !== false)\n clearRunRecord(projectRoot, host.name);\n });\n process.on(\"SIGINT\", () => onSignal(130));\n process.on(\"SIGTERM\", () => onSignal(143));\n }\n\n return { started, shutdown };\n}\n","import { z } from \"zod\";\n\n/**\n * The shared zod schemas for host.js blocks (D2.a). The `reactor` block\n * validates STRICTLY (D2.d — phase 0's tolerated-unknown-keys notice ends\n * here): a typo'd protocol key must fail, not silently not-apply, because\n * these are fleet-consensus settings. `config` stays loose — it is\n * runner-defined by design.\n */\n\nexport const profileSchema = z\n .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 .optional();\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 })\n .optional(),\n createSignaturePolicy: z.enum([\"legacy\", \"v2-required\"]).optional(),\n unsupportedStoredDocuments: z.enum([\"refuse\", \"read-only\"]).optional(),\n});\n\nexport const reactorBackendSchema = z.strictObject({\n kind: z.enum([\"in-process\", \"worker\", \"remote\"]).optional(),\n storage: z\n .strictObject({\n kind: z.enum([\"idb\", \"memory\", \"path\", \"postgres\"]),\n dataDir: 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 dynamic: z.boolean().optional(),\n })\n .optional(),\n remote: z\n .strictObject({\n host: z.string().optional(),\n url: z.string().optional(),\n })\n .optional(),\n});\n\nexport const reactorSchema = z.strictObject({\n backends: z.record(z.string(), reactorBackendSchema).optional(),\n placement: z\n .strictObject({\n primary: z.string().optional(),\n default: z.looseObject({}).optional(),\n })\n .optional(),\n workflows: z.boolean().optional(),\n protocol: reactorProtocolSchema.optional(),\n});\n\n/** Common runner options every host.runner carries; runner modules extend it\n * loosely with their own process options. */\nexport const runnerBaseSchema = z.looseObject({\n module: z.string().min(1),\n defaultVerb: z.string().optional(),\n port: z.number().int().positive().optional(),\n});\n\n/** A compound's children map (mutually exclusive with `reactor` — the XOR is\n * structural, enforced by the loader; schemas validate each side's shape). */\nexport const childrenSchema = z.record(\n z.string(),\n z.strictObject({\n host: z.string().min(1),\n plugins: z.array(z.string()).optional(),\n runner: z.looseObject({}).optional(),\n config: z.looseObject({}).optional(),\n reactor: reactorSchema.optional(),\n }),\n);\n\n/** Composed generic host shapes — the basis for the emitted editor schemas\n * (D2.a). Runner packages extend these with their own runner options; `config`\n * stays loose by design. */\nexport const reactorHostSchema = z.looseObject({\n name: z.string().min(1),\n runner: runnerBaseSchema,\n config: z.looseObject({}).optional(),\n profile: profileSchema,\n reactor: reactorSchema.optional(),\n});\n\nexport const compoundHostSchema = z.looseObject({\n name: z.string().min(1),\n runner: runnerBaseSchema,\n children: childrenSchema,\n config: z.looseObject({}).optional(),\n profile: profileSchema,\n});\n\nconst SCHEMA_BASE = \"https://powerhouse.inc/schemas\";\n\n/** The emitted-schema set, keyed by published filename. Pure — the\n * emit-schemas script writes these to disk and the drift test re-derives\n * them, per the runtime-config-schema pattern. */\nexport function emittedHostSchemas(): Record<string, unknown> {\n const emit = (name: string, schema: z.ZodType) => ({\n $id: `${SCHEMA_BASE}/${name}.schema.json`,\n ...z.toJSONSchema(schema, { io: \"input\" }),\n });\n return {\n \"host-reactor.schema.json\": emit(\"host-reactor\", reactorHostSchema),\n \"host-compound.schema.json\": emit(\"host-compound\", compoundHostSchema),\n };\n}\n"],"mappings":";;;;;;;;;;;;AAYA,SAAS,aACP,OAC0D;CAC1D,OAAO,WAAW;AACpB;AAKA,MAAM,YAAY,UAChB,aAAa,KAAK,IAAI,SAAS,MAAM,OAAO,MAAM;;;;;;;;AASpD,SAAgB,mBACd,GAAG,QACsB;CACzB,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,SAAS,QAClB,KAAK,MAAM,SAAS,OAAO;EACzB,MAAM,MAAM,SAAS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