@powerhousedao/ph-cli 6.2.3-dev.8 → 6.2.3-dev.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/dist/{auth-AR3VxAIk.mjs → auth-BFUq7CvE.mjs} +3 -3
  2. package/dist/{auth-AR3VxAIk.mjs.map → auth-BFUq7CvE.mjs.map} +1 -1
  3. package/dist/auth-CNhbN5UM.mjs +4 -0
  4. package/dist/build-t5pFQx0f.mjs +304 -0
  5. package/dist/build-t5pFQx0f.mjs.map +1 -0
  6. package/dist/build-wvc_NiGr.mjs +4 -0
  7. package/dist/check-ecwBLzrg.mjs +56 -0
  8. package/dist/check-ecwBLzrg.mjs.map +1 -0
  9. package/dist/{cli-connect-override-D3hh4aH_.mjs → cli-connect-override-DW7OYAGx.mjs} +39 -27
  10. package/dist/cli-connect-override-DW7OYAGx.mjs.map +1 -0
  11. package/dist/cli.d.mts +2 -1
  12. package/dist/cli.mjs +35 -1179
  13. package/dist/cli.mjs.map +1 -1
  14. package/dist/compound-C7GuPnTP-Ba4ce2Xa.mjs +2813 -0
  15. package/dist/compound-C7GuPnTP-Ba4ce2Xa.mjs.map +1 -0
  16. package/dist/connect-build-7nmQw9c5.mjs +253 -0
  17. package/dist/connect-build-7nmQw9c5.mjs.map +1 -0
  18. package/dist/{connect-config-BWGiW3IB.mjs → connect-config-CfQwxG8G.mjs} +19 -12
  19. package/dist/connect-config-CfQwxG8G.mjs.map +1 -0
  20. package/dist/connect-plugin-configs-CXN8_KL0.mjs +50 -0
  21. package/dist/connect-plugin-configs-CXN8_KL0.mjs.map +1 -0
  22. package/dist/connect-preview-Ckoqw_XU.mjs +231 -0
  23. package/dist/connect-preview-Ckoqw_XU.mjs.map +1 -0
  24. package/dist/connect-studio-Cac3eE_U.mjs +81 -0
  25. package/dist/connect-studio-Cac3eE_U.mjs.map +1 -0
  26. package/dist/connect-studio-Cf6UZvOo.mjs +4 -0
  27. package/dist/dist-DcARVrSg.mjs +643 -0
  28. package/dist/dist-DcARVrSg.mjs.map +1 -0
  29. package/dist/explain-Rx7JW1OU.mjs +230 -0
  30. package/dist/explain-Rx7JW1OU.mjs.map +1 -0
  31. package/dist/export-ZnJeAtLS.mjs +42 -0
  32. package/dist/export-ZnJeAtLS.mjs.map +1 -0
  33. package/dist/feature-flags-xwqcHEWC.mjs +4 -0
  34. package/dist/{generate-all-DrT4ZxHX.mjs → generate-all-5Om0CB4N.mjs} +9 -3
  35. package/dist/generate-all-5Om0CB4N.mjs.map +1 -0
  36. package/dist/generate-app-hm6CJ_4O.mjs +72 -0
  37. package/dist/generate-app-hm6CJ_4O.mjs.map +1 -0
  38. package/dist/generate-desktop-shell-DzEzNspp.mjs +318 -0
  39. package/dist/generate-desktop-shell-DzEzNspp.mjs.map +1 -0
  40. package/dist/generate-document-model-CiW13Vf7.mjs +60 -0
  41. package/dist/generate-document-model-CiW13Vf7.mjs.map +1 -0
  42. package/dist/generate-editor-kTiUOmDW.mjs +64 -0
  43. package/dist/generate-editor-kTiUOmDW.mjs.map +1 -0
  44. package/dist/generate-hosts-BFmPIW2X.mjs +18 -0
  45. package/dist/generate-hosts-BFmPIW2X.mjs.map +1 -0
  46. package/dist/generate-hosts-RWj7WPHZ.mjs +4 -0
  47. package/dist/generate-migration-file-yK8uA70U.mjs +20 -0
  48. package/dist/generate-migration-file-yK8uA70U.mjs.map +1 -0
  49. package/dist/generate-piece-C6ymlErL.mjs +73 -0
  50. package/dist/generate-piece-C6ymlErL.mjs.map +1 -0
  51. package/dist/generate-piece-action-DqR8BcoO.mjs +31 -0
  52. package/dist/generate-piece-action-DqR8BcoO.mjs.map +1 -0
  53. package/dist/generate-piece-trigger-CZaDD-cc.mjs +30 -0
  54. package/dist/generate-piece-trigger-CZaDD-cc.mjs.map +1 -0
  55. package/dist/generate-processor-BVjOsfjJ.mjs +58 -0
  56. package/dist/generate-processor-BVjOsfjJ.mjs.map +1 -0
  57. package/dist/generate-subgraph-CrHbYK91.mjs +64 -0
  58. package/dist/generate-subgraph-CrHbYK91.mjs.map +1 -0
  59. package/dist/get-version-CJulKHJ0.mjs +11 -0
  60. package/dist/get-version-CJulKHJ0.mjs.map +1 -0
  61. package/dist/index-CJN_BRkc.d.mts +4459 -0
  62. package/dist/index-CJN_BRkc.d.mts.map +1 -0
  63. package/dist/{init-BZP6gvYd.mjs → init-Ch1rCksS.mjs} +16 -12
  64. package/dist/init-Ch1rCksS.mjs.map +1 -0
  65. package/dist/{inspect-DXjbQEV_.mjs → inspect-zWJnBDMJ.mjs} +11 -4
  66. package/dist/inspect-zWJnBDMJ.mjs.map +1 -0
  67. package/dist/install-added-dependencies-DnZFR3aE.mjs +18 -0
  68. package/dist/install-added-dependencies-DnZFR3aE.mjs.map +1 -0
  69. package/dist/mcp-Cz9CubZa.mjs +262 -0
  70. package/dist/mcp-Cz9CubZa.mjs.map +1 -0
  71. package/dist/member-config-0tHtiVN_.mjs +154 -0
  72. package/dist/member-config-0tHtiVN_.mjs.map +1 -0
  73. package/dist/migrate-CIJaE3iZ.mjs +177 -0
  74. package/dist/migrate-CIJaE3iZ.mjs.map +1 -0
  75. package/dist/module-dir-1avCXsBi.mjs +17 -0
  76. package/dist/module-dir-1avCXsBi.mjs.map +1 -0
  77. package/dist/offered-routes-imports-CQInWI6y.mjs +4 -0
  78. package/dist/offered-routes-imports-CalXK9dh.mjs +96 -0
  79. package/dist/offered-routes-imports-CalXK9dh.mjs.map +1 -0
  80. package/dist/ph-cli-commands-C4gwBRyw.mjs +4 -0
  81. package/dist/ph-cli-commands-DFmTGL-H.mjs +1610 -0
  82. package/dist/ph-cli-commands-DFmTGL-H.mjs.map +1 -0
  83. package/dist/precompress-P6cJDPVC.mjs +77 -0
  84. package/dist/precompress-P6cJDPVC.mjs.map +1 -0
  85. package/dist/{registry-auth-DxEWCJu2.mjs → registry-auth-Bm5AR-fB.mjs} +4 -4
  86. package/dist/{registry-auth-DxEWCJu2.mjs.map → registry-auth-Bm5AR-fB.mjs.map} +1 -1
  87. package/dist/run-sugar-CRzZsmVo.mjs +39 -0
  88. package/dist/run-sugar-CRzZsmVo.mjs.map +1 -0
  89. package/dist/runners/connect.d.mts +1153 -0
  90. package/dist/runners/connect.d.mts.map +1 -0
  91. package/dist/runners/connect.mjs +300 -0
  92. package/dist/runners/connect.mjs.map +1 -0
  93. package/dist/runners/switchboard.d.mts +1481 -0
  94. package/dist/runners/switchboard.d.mts.map +1 -0
  95. package/dist/runners/switchboard.mjs +550 -0
  96. package/dist/runners/switchboard.mjs.map +1 -0
  97. package/dist/schemas-ByfuhvAb.mjs +5752 -0
  98. package/dist/schemas-ByfuhvAb.mjs.map +1 -0
  99. package/dist/scripts/emit-runner-schemas.ts +24 -0
  100. package/dist/scripts/generate-commands-docs.ts +12 -0
  101. package/dist/scripts/manage-environment +0 -0
  102. package/dist/scripts/setup.sh +0 -0
  103. package/dist/start-run-CRVBqQ8L.mjs +124 -0
  104. package/dist/start-run-CRVBqQ8L.mjs.map +1 -0
  105. package/dist/superseded-config-CbSTFun2.mjs +53 -0
  106. package/dist/superseded-config-CbSTFun2.mjs.map +1 -0
  107. package/dist/switchboard-B7mvNWcd.mjs +4 -0
  108. package/dist/switchboard-Cqs5IBNF.mjs +168 -0
  109. package/dist/switchboard-Cqs5IBNF.mjs.map +1 -0
  110. package/dist/{switchboard-migrate-NQ7LHWSi.mjs → switchboard-migrate-Docb8Cjv.mjs} +6 -5
  111. package/dist/{switchboard-migrate-NQ7LHWSi.mjs.map → switchboard-migrate-Docb8Cjv.mjs.map} +1 -1
  112. package/dist/switchboard-proxy-CGfMtENM.mjs +37 -0
  113. package/dist/switchboard-proxy-CGfMtENM.mjs.map +1 -0
  114. package/dist/{switchboard-reset-BcQXlcVf.mjs → switchboard-reset-MtTB_GAI.mjs} +8 -6
  115. package/dist/switchboard-reset-MtTB_GAI.mjs.map +1 -0
  116. package/dist/sync-connect-routes-BtAsFPXN.mjs +4 -0
  117. package/dist/sync-connect-routes-t0Slg-P6.mjs +25 -0
  118. package/dist/sync-connect-routes-t0Slg-P6.mjs.map +1 -0
  119. package/dist/{utils-C4isxXSO.mjs → utils-9KyRM0mf.mjs} +6 -34
  120. package/dist/{utils-C4isxXSO.mjs.map → utils-9KyRM0mf.mjs.map} +1 -1
  121. package/dist/utils-DAux4Ga7.mjs +4 -0
  122. package/dist/{vetra-DkF6EJMY.mjs → vetra-DZYtcHqV.mjs} +130 -147
  123. package/dist/vetra-DZYtcHqV.mjs.map +1 -0
  124. package/dist/vetra-launch-DQDZxGTV.mjs +343 -0
  125. package/dist/vetra-launch-DQDZxGTV.mjs.map +1 -0
  126. package/dist/warn-subgraph-type-conflicts-BOHBmThq.mjs +19 -0
  127. package/dist/warn-subgraph-type-conflicts-BOHBmThq.mjs.map +1 -0
  128. package/package.json +42 -18
  129. package/dist/auth-BNkN6kS9.mjs +0 -4
  130. package/dist/build-C-A5-ipO.mjs +0 -4
  131. package/dist/build-uQXq6_HU.mjs +0 -71
  132. package/dist/build-uQXq6_HU.mjs.map +0 -1
  133. package/dist/cli-connect-override-D3hh4aH_.mjs.map +0 -1
  134. package/dist/connect-build-WL4axo4z.mjs +0 -43
  135. package/dist/connect-build-WL4axo4z.mjs.map +0 -1
  136. package/dist/connect-config-BWGiW3IB.mjs.map +0 -1
  137. package/dist/connect-preview-D7ypzFDc.mjs +0 -28
  138. package/dist/connect-preview-D7ypzFDc.mjs.map +0 -1
  139. package/dist/connect-studio-BIQzyq5B.mjs +0 -5
  140. package/dist/connect-studio-D6rfWCNB.mjs +0 -31
  141. package/dist/connect-studio-D6rfWCNB.mjs.map +0 -1
  142. package/dist/generate-all-DrT4ZxHX.mjs.map +0 -1
  143. package/dist/generate-app-DNNqA-H3.mjs +0 -48
  144. package/dist/generate-app-DNNqA-H3.mjs.map +0 -1
  145. package/dist/generate-document-model-BJXyODfm.mjs +0 -34
  146. package/dist/generate-document-model-BJXyODfm.mjs.map +0 -1
  147. package/dist/generate-editor-BejvaVVT.mjs +0 -48
  148. package/dist/generate-editor-BejvaVVT.mjs.map +0 -1
  149. package/dist/generate-processor-_WOx-mMe.mjs +0 -40
  150. package/dist/generate-processor-_WOx-mMe.mjs.map +0 -1
  151. package/dist/generate-subgraph-BsHUstpl.mjs +0 -38
  152. package/dist/generate-subgraph-BsHUstpl.mjs.map +0 -1
  153. package/dist/init-BZP6gvYd.mjs.map +0 -1
  154. package/dist/inspect-DXjbQEV_.mjs.map +0 -1
  155. package/dist/migrate-jGKfE02L.mjs +0 -83
  156. package/dist/migrate-jGKfE02L.mjs.map +0 -1
  157. package/dist/switchboard-CJMoMzWx.mjs +0 -75
  158. package/dist/switchboard-CJMoMzWx.mjs.map +0 -1
  159. package/dist/switchboard-iRFugh8I.mjs +0 -4
  160. package/dist/switchboard-reset-BcQXlcVf.mjs.map +0 -1
  161. package/dist/utils-BzwczAW-.mjs +0 -4
  162. package/dist/vetra-DkF6EJMY.mjs.map +0 -1
@@ -0,0 +1,2813 @@
1
+
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="57a0cfdd-936e-5667-92af-0b7932191a13")}catch(e){}}();
3
+ import { c as number, d as string, f as union, g as prettifyError, h as toJSONSchema, i as boolean, l as record, m as url, n as _enum, o as literal, p as unknown, r as array, s as looseObject, t as ZodType, u as strictObject } from "./schemas-ByfuhvAb.mjs";
4
+ import { createRequire } from "node:module";
5
+ import fs, { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
6
+ import path from "node:path";
7
+ import { isOriginPlaceholderUrl } from "@powerhousedao/shared/connect/origin-placeholder";
8
+ import { createHash } from "node:crypto";
9
+ import { pathToFileURL } from "node:url";
10
+ import { TOKEN_ESCAPE_KEY, envTokenable, findToken, isToken, switchboardOfDrive, tokenKeyOf, tokenSchema, tokenable } from "@powerhousedao/shared/host-tokens";
11
+ import { resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
12
+ //#region ../../packages/host-core/dist/compound-C7GuPnTP.mjs
13
+ /**
14
+ * R1 — the host plugin framework (bridge-runners-to-plugins plan,
15
+ * customization-references/host-core as the blueprint).
16
+ *
17
+ * A plugin is hooks + contributions; hooks are boot wiring (main realm only),
18
+ * contributions are declarative, serializable surface. Host RUNTIMES define
19
+ * the hook vocabulary and interleave their own wiring between stages — they
20
+ * are never plugins themselves.
21
+ *
22
+ * host.js carries the COMPOSITION as `runner.plugins` entries:
23
+ * string | { module, enabled?, verbs?, config? }
24
+ * Presence is activation (enabled defaults true); `verbs` scopes an entry to
25
+ * matching run verbs; `config` is validated against the plugin's declared
26
+ * zod schema. Entries resolve from the PROJECT's dependency tree exactly
27
+ * like runner modules.
28
+ */
29
+ var PluginError = class extends Error {
30
+ constructor(message, hint) {
31
+ super(hint ? `${message}\n Hint: ${hint}` : message);
32
+ this.name = "PluginError";
33
+ }
34
+ };
35
+ const pluginEntryObjectSchema = strictObject({
36
+ module: string().min(1),
37
+ /** Presence is activation BY DEFAULT; false is the explicit off-switch. */
38
+ enabled: boolean().optional(),
39
+ /** "*" (default) or the run verbs this entry is active for. */
40
+ verbs: union([literal("*"), array(string().min(1)).min(1)]).optional(),
41
+ /** Validated against the plugin's declared configSchema at resolution. */
42
+ config: record(string(), unknown()).optional()
43
+ });
44
+ const pluginEntrySchema = union([string().min(1), pluginEntryObjectSchema]);
45
+ function normalizePluginEntry(entry) {
46
+ if (typeof entry === "string") return {
47
+ module: entry,
48
+ enabled: true,
49
+ verbs: "*",
50
+ config: {}
51
+ };
52
+ return {
53
+ module: entry.module,
54
+ enabled: entry.enabled ?? true,
55
+ verbs: entry.verbs ?? "*",
56
+ config: entry.config ?? {}
57
+ };
58
+ }
59
+ /** Module is the identity key: a duplicate makes override targeting and
60
+ * ordering ambiguous, so it fails loudly. */
61
+ function normalizePluginEntries(entries, where) {
62
+ const normalized = entries.map(normalizePluginEntry);
63
+ const seen = /* @__PURE__ */ new Set();
64
+ for (const entry of normalized) {
65
+ 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.");
66
+ seen.add(entry.module);
67
+ }
68
+ return normalized;
69
+ }
70
+ function entryActiveForVerb(entry, verb) {
71
+ if (!entry.enabled) return false;
72
+ return entry.verbs === "*" || entry.verbs.includes(verb);
73
+ }
74
+ /**
75
+ * The appliesTo hierarchy. "reactor" is the base every reactor host extends;
76
+ * "compound" is its own branch (plugins over the member set — e.g. the clint
77
+ * proxy). Host runtimes register their id with a parent; compatibility walks
78
+ * the parent chain.
79
+ */
80
+ const HOST_TYPE_PARENTS = {
81
+ reactor: null,
82
+ compound: null,
83
+ connect: "reactor",
84
+ switchboard: "reactor",
85
+ mastra: "reactor"
86
+ };
87
+ function hostTypeSatisfies(hostType, appliesTo) {
88
+ let current = hostType;
89
+ while (current !== null) {
90
+ if (current === appliesTo) return true;
91
+ current = current in HOST_TYPE_PARENTS ? HOST_TYPE_PARENTS[current] : null;
92
+ }
93
+ return false;
94
+ }
95
+ /**
96
+ * NODE-ONLY plugin resolution (split from plugins.ts so the pure runner core
97
+ * stays browser-safe for ConnectCore — R3). Resolves host.js entries from the
98
+ * PROJECT dependency tree, exactly like runner modules.
99
+ */
100
+ function isHostPluginShape(value) {
101
+ return value !== null && typeof value === "object" && typeof value.name === "string";
102
+ }
103
+ /**
104
+ * Resolve host.js plugin entries into live plugins for one host boot:
105
+ * verb-filter → module resolution from the project tree (default condition,
106
+ * like runners) → factory/object contract → config validation → appliesTo.
107
+ */
108
+ async function resolveHostPlugins(projectRoot, hostType, verb, entries, where) {
109
+ const normalized = normalizePluginEntries(entries, where);
110
+ const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
111
+ const resolved = [];
112
+ for (const entry of normalized) {
113
+ if (!entryActiveForVerb(entry, verb)) continue;
114
+ let file;
115
+ try {
116
+ file = projectRequire.resolve(entry.module);
117
+ } catch {
118
+ throw new PluginError(`${where}: cannot resolve plugin "${entry.module}" from ${projectRoot}.`, "Plugins resolve from the project dependency tree, exactly like runner modules.");
119
+ }
120
+ const exported = (await import(pathToFileURL(file).href)).default;
121
+ let plugin;
122
+ if (typeof exported === "function") plugin = exported(entry.config);
123
+ else if (isHostPluginShape(exported)) {
124
+ if (Object.keys(entry.config).length > 0 && !exported.configSchema) throw new PluginError(`${where}: plugin "${entry.module}" takes no config, but the entry passes one.`);
125
+ plugin = exported;
126
+ } else throw new PluginError(`${where}: "${entry.module}" does not default-export a plugin object or factory.`, "Export `{ name, hooks?, contributions? }` or `(config) => plugin`.");
127
+ if (plugin.configSchema) {
128
+ const parsed = plugin.configSchema.safeParse(entry.config);
129
+ if (!parsed.success) throw new PluginError(`${where}: config for plugin "${plugin.name}" is invalid:\n` + prettifyError(parsed.error));
130
+ }
131
+ const appliesTo = plugin.appliesTo ?? "reactor";
132
+ if (!hostTypeSatisfies(hostType, appliesTo)) throw new PluginError(`${where}: plugin "${plugin.name}" applies to "${appliesTo}" hosts, but this host is "${hostType}".`);
133
+ resolved.push({
134
+ entry,
135
+ plugin,
136
+ provenance: "dependency"
137
+ });
138
+ }
139
+ return resolved;
140
+ }
141
+ /**
142
+ * LENIENT resolution for diagnostics (`ph run <host> --explain drives`):
143
+ * collects the drive contributions of the entries active for `verb`. Unlike
144
+ * resolveHostPlugins it does not know the host type (so appliesTo is not
145
+ * checked) and does not fail on a specifier the project tree cannot resolve
146
+ * — the entry is listed under `unresolved` instead. Config is still validated
147
+ * against the plugin's schema, so a bad entry surfaces here too.
148
+ */
149
+ async function resolvePluginContributions(projectRoot, verb, entries, where) {
150
+ const normalized = normalizePluginEntries(entries, where);
151
+ const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
152
+ const plan = {
153
+ drives: [],
154
+ unresolved: []
155
+ };
156
+ for (const entry of normalized) {
157
+ if (!entryActiveForVerb(entry, verb)) continue;
158
+ let file;
159
+ try {
160
+ file = projectRequire.resolve(entry.module);
161
+ } catch {
162
+ plan.unresolved.push(entry.module);
163
+ continue;
164
+ }
165
+ const exported = (await import(pathToFileURL(file).href)).default;
166
+ let plugin;
167
+ if (typeof exported === "function") plugin = exported(entry.config);
168
+ else if (isHostPluginShape(exported)) plugin = exported;
169
+ else {
170
+ plan.unresolved.push(entry.module);
171
+ continue;
172
+ }
173
+ if (plugin.configSchema) {
174
+ const parsed = plugin.configSchema.safeParse(entry.config);
175
+ if (!parsed.success) throw new PluginError(`${where}: config for plugin "${plugin.name}" is invalid:\n` + prettifyError(parsed.error));
176
+ }
177
+ for (const declaration of plugin.contributions?.drives ?? []) plan.drives.push({
178
+ declaration,
179
+ source: plugin.name
180
+ });
181
+ }
182
+ return plan;
183
+ }
184
+ /**
185
+ * The connect config slices each built-in Connect plugin owns, by specifier
186
+ * (typed-host-configs 1.6). Under a declared composition Connect zeroes a
187
+ * slice whose plugin is absent — presence is activation — so an authored
188
+ * value there is dead config. Connect's built-ins are browser modules with no
189
+ * Node-resolvable identity, so their ownership is declared here as data; a
190
+ * Connect test pins it to plugin-host's zeroing.
191
+ */
192
+ const CONNECT_PLUGIN_OWNED_SLICES = {
193
+ "@powerhousedao/connect/plugins/generic": { slices: [
194
+ {
195
+ path: "drives.allowAddDrive",
196
+ absent: false,
197
+ entryKey: "allowAddDrive"
198
+ },
199
+ {
200
+ path: "drives.sections",
201
+ absent: {
202
+ remote: {
203
+ enabled: false,
204
+ allowAdd: false,
205
+ allowDelete: false
206
+ },
207
+ local: {
208
+ enabled: false,
209
+ allowAdd: false,
210
+ allowDelete: false
211
+ }
212
+ },
213
+ entryKey: "sections"
214
+ },
215
+ {
216
+ path: "drives.icons",
217
+ absent: null,
218
+ entryKey: "icons"
219
+ },
220
+ {
221
+ path: "home.background",
222
+ absent: null,
223
+ entryKey: "homeBackground"
224
+ }
225
+ ] },
226
+ "@powerhousedao/connect/plugins/sentry": { slices: [{
227
+ path: "sentry.dsn",
228
+ absent: null,
229
+ entryKey: "dsn"
230
+ }] },
231
+ "@powerhousedao/connect/plugins/openpanel": {
232
+ slices: [
233
+ {
234
+ path: "openPanel.clientId",
235
+ absent: "",
236
+ entryKey: "clientId"
237
+ },
238
+ {
239
+ path: "openPanel.trackUiEvents",
240
+ absent: false,
241
+ entryKey: "trackUiEvents"
242
+ },
243
+ {
244
+ path: "openPanel.trackOperations",
245
+ absent: false,
246
+ entryKey: "trackOperations"
247
+ }
248
+ ],
249
+ inertUnless: "openPanel.clientId"
250
+ },
251
+ "@powerhousedao/connect/plugins/assistant": { slices: [{
252
+ path: "ai.assistantEnabled",
253
+ absent: false
254
+ }] },
255
+ "@powerhousedao/vetra-studio/connect": { slices: [{
256
+ path: "app.studioMode",
257
+ absent: false
258
+ }] },
259
+ "@powerhousedao/connect/plugins/workflows": { slices: [{
260
+ path: "app.workflowsEnabled",
261
+ absent: false
262
+ }] }
263
+ };
264
+ function valueAt$1(root, dotted) {
265
+ let current = root;
266
+ for (const key of dotted.split(".")) {
267
+ if (current === null || typeof current !== "object") return void 0;
268
+ current = current[key];
269
+ }
270
+ return current;
271
+ }
272
+ /** Whether Connect already serves what the author wrote: every authored leaf
273
+ * equals the served one. An unset leaf asks for nothing, so a partial object
274
+ * (`sections: { remote: { enabled: false } }`) is satisfied by the zeroed
275
+ * slice. */
276
+ function alreadyServed(authored, served) {
277
+ if (authored === void 0 || Object.is(authored, served)) return true;
278
+ if (authored === null || served === null || typeof authored !== "object" || typeof served !== "object" || Array.isArray(authored) !== Array.isArray(served)) return false;
279
+ if (Array.isArray(authored) && authored.length !== served.length) return false;
280
+ const want = authored;
281
+ const have = served;
282
+ return Object.keys(want).every((key) => alreadyServed(want[key], have[key]));
283
+ }
284
+ /**
285
+ * Dead-config warnings for a Connect host (typed-host-configs 1.6): an
286
+ * authored connect config value whose owning plugin is not in the
287
+ * composition active for `verb`. Connect zeroes such a slice, so the value
288
+ * has no effect — e.g. Sektar's `connect.drives.allowAddDrive: true` without
289
+ * the generic plugin.
290
+ *
291
+ * Nothing is reported when the host declares no composition
292
+ * (`runner.plugins` absent: the classic boot serves the config as is), or
293
+ * when Connect already serves every leaf of the authored value. Warnings, not
294
+ * errors: the host still boots, it just does not do what the value says.
295
+ */
296
+ function findDeadConnectConfig(config, entries, verb, where) {
297
+ if (!config || entries === void 0) return [];
298
+ const active = new Set(normalizePluginEntries(entries, where).filter((entry) => entryActiveForVerb(entry, verb)).map((entry) => entry.module));
299
+ const warnings = [];
300
+ for (const [owner, { slices, inertUnless }] of Object.entries(CONNECT_PLUGIN_OWNED_SLICES)) {
301
+ if (active.has(owner)) continue;
302
+ if (inertUnless !== void 0) {
303
+ const gate = slices.find((slice) => slice.path === inertUnless);
304
+ if (alreadyServed(valueAt$1(config, inertUnless), gate?.absent)) continue;
305
+ }
306
+ for (const { path: slicePath, absent, entryKey } of slices) {
307
+ const value = valueAt$1(config, slicePath);
308
+ if (alreadyServed(value, absent)) continue;
309
+ const move = entryKey === void 0 ? `compose "${owner}" (presence is the switch)` : `compose "${owner}" and set \`${entryKey}\` in its entry config`;
310
+ warnings.push({
311
+ path: slicePath,
312
+ value,
313
+ served: absent,
314
+ owner,
315
+ message: `${where}: config.${slicePath} is dead config: it is owned by plugin "${owner}", which this host does not compose for verb "${verb}", so Connect serves ${JSON.stringify(absent)} instead of ${JSON.stringify(value)}.\n Hint: ${move}, or delete the value.`
316
+ });
317
+ }
318
+ }
319
+ return warnings;
320
+ }
321
+ /**
322
+ * The schema half of drives.ts, zod only so `./schema` stays neutral.
323
+ * - slug: the SEEDING KEY (idempotence); id optional (stable identity).
324
+ * - preferredEditor: stored at header.meta.preferredEditor; Connect config's
325
+ * `app` is the legacy alias.
326
+ * - remote.url: a drive served elsewhere; local fields are ignored for it.
327
+ * Token-able (`$output` on a producer's `drives.<slug>.url`).
328
+ */
329
+ function buildDriveDeclarationSchema(urlField) {
330
+ return strictObject({
331
+ slug: string().min(1),
332
+ id: string().min(1).optional(),
333
+ /** Derive the id from the project path, like generateProjectDriveId — the
334
+ * same ids classic `ph vetra` produces. `true` serves the drive under the
335
+ * hashed slug too (the vetra drive's slug IS its hashed id); `"id"` hashes
336
+ * only the id and keeps the declared slug (the classic Workflows drive:
337
+ * `/d/workflows`, id `workflows-<hash>`). */
338
+ projectHash: union([boolean(), literal("id")]).optional(),
339
+ name: string().min(1).optional(),
340
+ icon: string().optional(),
341
+ preferredEditor: string().optional(),
342
+ sharingType: _enum([
343
+ "public",
344
+ "private",
345
+ "shared"
346
+ ]).optional(),
347
+ availableOffline: boolean().optional(),
348
+ remote: strictObject({ url: urlField(string().min(1)) }).optional()
349
+ });
350
+ }
351
+ const driveDeclarationSchema = buildDriveDeclarationSchema(tokenable);
352
+ const drivesSchema = array(driveDeclarationSchema);
353
+ /** The project-hashed drive id (`${slug}-${sha256(projectRoot)[0..8]}`) with
354
+ * the hash function injected, so neutral consumers (a browser monitor) can
355
+ * pass `crypto.subtle`-derived or precomputed hex. drives.ts binds it to
356
+ * node:crypto as `projectDriveId`. */
357
+ function projectDriveIdWith(sha256Hex, projectRoot, slug) {
358
+ return `${slug}-${sha256Hex(projectRoot).substring(0, 8)}`;
359
+ }
360
+ /**
361
+ * The zod single source for host.js blocks (typed-host-configs G1). Every
362
+ * host type is z.input/z.output of these schemas; nothing is hand-mirrored.
363
+ * Top-level host objects and the `reactor` block are STRICT (a typo fails);
364
+ * `runner` stays loose until each runner declares its options (T2), and
365
+ * `config` is runner-defined.
366
+ *
367
+ * Token-able fields (typed-host-configs 3.5): `reactor.backends.*.remote.url`
368
+ * (required, a switchboard drive address), `reactor.drives` (whole list, e.g. `$map`),
369
+ * `reactor.drives[].remote.url` and `storage.dataDir` (`$env` only). Their z.input admits tokens, their z.output is the resolved type.
370
+ */
371
+ /** A host's `name` keys its run record, `.ph/run/<name>.json`, so it must be
372
+ * one safe path segment. */
373
+ const HOST_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
374
+ const HOST_NAME_MESSAGE = "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.";
375
+ const hostNameSchema = string().min(1).max(128, HOST_NAME_MESSAGE).regex(HOST_NAME_PATTERN, HOST_NAME_MESSAGE);
376
+ /**
377
+ * A URL, or one written against the page origin (`${origin}/graphql`): the
378
+ * browser resolves the placeholder when it loads Connect's config, for a
379
+ * member whose own server proxies the switchboard's paths.
380
+ */
381
+ const originOrUrlSchema = union([url(), string().refine(isOriginPlaceholderUrl, { message: "a URL, or ${origin}/<path> for a proxied sibling" })]);
382
+ const profileSchema = strictObject({
383
+ appId: string().min(1).optional(),
384
+ name: string().min(1).optional(),
385
+ description: string().optional(),
386
+ icon: string().optional()
387
+ });
388
+ const reactorProtocolSchema = strictObject({
389
+ featureFlags: strictObject({
390
+ documentDecisions: boolean().optional(),
391
+ authEnforcement: boolean().optional(),
392
+ authGroups: boolean().optional(),
393
+ authConditions: boolean().optional()
394
+ }).optional(),
395
+ createSignaturePolicy: _enum(["legacy", "v2-required"]).optional(),
396
+ unsupportedStoredDocuments: _enum(["refuse", "read-only"]).optional()
397
+ });
398
+ const runnerKindSchema = _enum(["reactor", "compound"]);
399
+ const reactorBackendKindSchema = _enum([
400
+ "in-process",
401
+ "worker",
402
+ "remote"
403
+ ]);
404
+ const samePath = (a, b) => {
405
+ const norm = (p) => p.replace(/\\/g, "/").replace(/\/+$/, "").replace(/^\.\//, "");
406
+ return norm(a) === norm(b);
407
+ };
408
+ /** Compound wiring: the generic compound runner's `config` block.
409
+ * (`projectDrivesIntoConnect` and `drivesPublicBase` were removed in T3: a
410
+ * member consumes another member's drives through `$output` tokens.) */
411
+ const compoundWiringSchema = strictObject({
412
+ /** Member start order; must name declared children and agree with the
413
+ * output-token dependencies (resolve/plan.ts). Optional: without it the
414
+ * order is derived from the tokens. Unnamed members start after the named
415
+ * ones, in declaration order. */
416
+ startOrder: array(string().min(1)).optional(),
417
+ /** Write .ph/run/<host>.json (default true). */
418
+ runtimeRecord: boolean().optional(),
419
+ /** Patch the baked CSP for the runtime registry on a served Connect
420
+ * member (forwarded as `runner.cspRegistrySync` to every member whose
421
+ * runner is `@powerhousedao/ph-cli/runners/connect`). */
422
+ cspRegistrySync: boolean().optional()
423
+ });
424
+ /** `config.startOrder ⊆ keys(children)`, checked where both are visible.
425
+ * Apply it LAST (`.superRefine(refineStartOrder)`) to a runner's final host
426
+ * schema: zod refuses to `.extend()` a refined object. */
427
+ function refineStartOrder(host, ctx) {
428
+ const startOrder = host.config?.startOrder;
429
+ if (!Array.isArray(startOrder)) return;
430
+ const members = Object.keys(host.children);
431
+ startOrder.forEach((name, index) => {
432
+ if (startOrder.indexOf(name) !== index) {
433
+ ctx.addIssue({
434
+ code: "custom",
435
+ path: [
436
+ "config",
437
+ "startOrder",
438
+ index
439
+ ],
440
+ message: `startOrder names "${String(name)}" twice; each member starts once.`
441
+ });
442
+ return;
443
+ }
444
+ if (typeof name === "string" && members.includes(name)) return;
445
+ ctx.addIssue({
446
+ code: "custom",
447
+ path: [
448
+ "config",
449
+ "startOrder",
450
+ index
451
+ ],
452
+ message: `startOrder names "${String(name)}", which is not a member. Members: ${members.join(", ") || "(none)"}.`
453
+ });
454
+ });
455
+ }
456
+ const ALLOW_TOKENS = {
457
+ any: tokenable,
458
+ env: envTokenable
459
+ };
460
+ const FORBID_TOKENS = {
461
+ any: (schema) => union([schema]),
462
+ env: (schema) => union([schema])
463
+ };
464
+ /** The replacement a non-drive `remote.url` message names. */
465
+ function useDriveUrl(host = "switchboard", member) {
466
+ return `remote: { url: ${host}.drives.<slug>.url } with ${host} from ../${host}/outputs.js, or remote: { url: { $output: { host: "${host}"${member ? `, member: "${member}"` : ""}, path: ["drives", "<slug>", "url"] } } }`;
467
+ }
468
+ /** The `$output` of a declared `remote.url` that reads `endpoints.graphql`. */
469
+ function endpointsGraphqlRef(url) {
470
+ if (typeof url !== "object" || url === null || !("$output" in url)) return;
471
+ const ref = url.$output;
472
+ if (typeof ref !== "object" || ref === null) return void 0;
473
+ const { host, member, path } = ref;
474
+ if (typeof host !== "string" || !Array.isArray(path)) return void 0;
475
+ if (path.join(".") !== "endpoints.graphql") return void 0;
476
+ return {
477
+ host,
478
+ ...typeof member === "string" ? { member } : {}
479
+ };
480
+ }
481
+ /** The slug a drive link names: a `drives.<slug>.url` token's slug or a
482
+ * literal address's served slug; undefined when only runtime knows it. */
483
+ function linkedSlug(url) {
484
+ if (typeof url === "string") return switchboardOfDrive(url)?.slug;
485
+ const ref = typeof url === "object" && url !== null && "$output" in url ? url.$output : void 0;
486
+ const path = Array.isArray(ref?.path) ? ref.path : [];
487
+ return path.length === 3 && path[0] === "drives" && typeof path[1] === "string" && path[2] === "url" ? path[1] : void 0;
488
+ }
489
+ /** The drives a declared host names (home drives, `reactor.drives`, plugin
490
+ * `config.drive` links), or undefined when one is known only at runtime. */
491
+ function knownDriveSlugs(host) {
492
+ const reactor = host.reactor ?? {};
493
+ const slugs = [];
494
+ for (const backend of Object.values(reactor.backends ?? {})) {
495
+ if (backend.kind !== "remote") continue;
496
+ const slug = linkedSlug(backend.remote?.url);
497
+ if (slug === void 0) return void 0;
498
+ slugs.push(slug);
499
+ }
500
+ if (reactor.drives !== void 0) {
501
+ if (!Array.isArray(reactor.drives)) return void 0;
502
+ for (const drive of reactor.drives) if (typeof drive.slug === "string") slugs.push(drive.slug);
503
+ }
504
+ const plugins = Array.isArray(host.runner?.plugins) ? host.runner.plugins : [];
505
+ for (const entry of plugins) {
506
+ const config = typeof entry === "object" && entry !== null && "config" in entry ? entry.config : void 0;
507
+ if (typeof config !== "object" || config === null) continue;
508
+ if (!("drive" in config) || config.drive === void 0) continue;
509
+ const slug = linkedSlug(config.drive);
510
+ if (slug === void 0) return void 0;
511
+ slugs.push(slug);
512
+ }
513
+ return slugs;
514
+ }
515
+ /** Declared form, at host level so plugin drives are seen: a placement key
516
+ * must name a drive the host names, when every drive is knowable. A host
517
+ * with no remote backend is not checked: its plugins may contribute drives
518
+ * (a switchboard's workflows drive) that no field names. */
519
+ function refineDeclaredPlacementKeys(host, ctx) {
520
+ const placed = Object.keys(host.reactor?.placement?.drives ?? {});
521
+ if (placed.length === 0) return;
522
+ if (!Object.values(host.reactor?.backends ?? {}).some((b) => b.kind === "remote")) return;
523
+ const known = knownDriveSlugs(host);
524
+ if (!known) return;
525
+ const names = (slug, served) => served === slug || served.startsWith(`${slug}-`) && /^[0-9a-f]{8}$/.test(served.slice(slug.length + 1));
526
+ for (const slug of placed) {
527
+ if (known.some((served) => names(slug, served))) continue;
528
+ ctx.addIssue({
529
+ code: "custom",
530
+ path: [
531
+ "reactor",
532
+ "placement",
533
+ "drives",
534
+ slug
535
+ ],
536
+ message: `placement.drives.${slug} names no drive this host links to or declares (${[...new Set(known)].join(", ") || "none"}).`
537
+ });
538
+ }
539
+ }
540
+ /** Resolved-form checks across backends, drives and placement: one base is
541
+ * one remote backend, and a drive placed on a remote is on its switchboard. */
542
+ function refineResolvedReactor(reactor, ctx) {
543
+ const backends = reactor.backends ?? {};
544
+ const baseOf = /* @__PURE__ */ new Map();
545
+ const byBase = /* @__PURE__ */ new Map();
546
+ const linked = /* @__PURE__ */ new Map();
547
+ const link = (slug, base) => linked.set(slug, (linked.get(slug) ?? /* @__PURE__ */ new Set()).add(base));
548
+ for (const [name, backend] of Object.entries(backends)) {
549
+ const url = backend.remote?.url;
550
+ if (backend.kind !== "remote" || typeof url !== "string") continue;
551
+ const home = switchboardOfDrive(url);
552
+ if (!home) continue;
553
+ baseOf.set(name, home.base);
554
+ link(home.slug, home.base);
555
+ const first = byBase.get(home.base);
556
+ if (first === void 0) {
557
+ byBase.set(home.base, name);
558
+ continue;
559
+ }
560
+ ctx.addIssue({
561
+ code: "custom",
562
+ path: [
563
+ "backends",
564
+ name,
565
+ "remote",
566
+ "url"
567
+ ],
568
+ 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.`
569
+ });
570
+ }
571
+ const kept = /* @__PURE__ */ new Set();
572
+ (Array.isArray(reactor.drives) ? reactor.drives : []).forEach((drive, index) => {
573
+ if (!drive.remote) {
574
+ kept.add(drive.slug);
575
+ return;
576
+ }
577
+ const at = switchboardOfDrive(drive.remote.url);
578
+ if (at || drive.remote.url === "") {
579
+ if (at) link(drive.slug, at.base);
580
+ return;
581
+ }
582
+ ctx.addIssue({
583
+ code: "custom",
584
+ path: [
585
+ "drives",
586
+ index,
587
+ "remote",
588
+ "url"
589
+ ],
590
+ 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"] } }.`
591
+ });
592
+ });
593
+ const nameOf = (base) => byBase.get(base) ?? base;
594
+ for (const [slug, name] of Object.entries(reactor.placement?.drives ?? {})) {
595
+ const at = [
596
+ "placement",
597
+ "drives",
598
+ slug
599
+ ];
600
+ const on = [...linked.get(slug) ?? []];
601
+ if (on.length > 0 && kept.has(slug)) {
602
+ ctx.addIssue({
603
+ code: "custom",
604
+ path: at,
605
+ message: `Drive "${slug}" is both this reactor's own drive and on ${on.map(nameOf).join(" and ")}. Rename one, or link only one.`
606
+ });
607
+ continue;
608
+ }
609
+ if (on.length > 1) {
610
+ ctx.addIssue({
611
+ code: "custom",
612
+ path: at,
613
+ message: `Drive "${slug}" is on both ${on.map(nameOf).join(" and ")}. Rename one, or link only one.`
614
+ });
615
+ continue;
616
+ }
617
+ const base = baseOf.get(name);
618
+ if (base === void 0) continue;
619
+ if (on.length === 0) {
620
+ if (!kept.has(slug)) continue;
621
+ ctx.addIssue({
622
+ code: "custom",
623
+ path: at,
624
+ 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.`
625
+ });
626
+ continue;
627
+ }
628
+ if (on[0] === base) continue;
629
+ ctx.addIssue({
630
+ code: "custom",
631
+ path: at,
632
+ 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.`
633
+ });
634
+ }
635
+ }
636
+ /**
637
+ * Builds the host schema set. "allow" (declared form) accepts `T | Token` in
638
+ * every token-able field; "forbid" (resolved form) accepts `T` only.
639
+ */
640
+ function buildHostSchemas(tokenField) {
641
+ const resolved = tokenField === FORBID_TOKENS;
642
+ const reactorBackendSchema = strictObject({
643
+ kind: reactorBackendKindSchema,
644
+ storage: strictObject({
645
+ kind: _enum([
646
+ "idb",
647
+ "memory",
648
+ "path",
649
+ "postgres"
650
+ ]),
651
+ /** `"${userData}/…"` sugar or `{ $env: "NAME" }`. */
652
+ dataDir: tokenField.env(string()).optional(),
653
+ url: string().optional()
654
+ }).optional(),
655
+ readModel: strictObject({ url: string().optional() }).optional(),
656
+ packages: strictObject({
657
+ cdnUrl: string().optional(),
658
+ specs: array(string()).optional(),
659
+ /** on-demand model resolution (was DYNAMIC_MODEL_LOADING). */
660
+ dynamic: boolean().optional()
661
+ }).optional(),
662
+ remote: strictObject({ url: tokenField.any(originOrUrlSchema) }).optional()
663
+ }).superRefine((backend, ctx) => {
664
+ if (backend.kind === "remote" && !backend.remote) ctx.addIssue({
665
+ code: "custom",
666
+ path: ["remote", "url"],
667
+ message: `a "remote" backend needs remote.url, a switchboard drive address: ${useDriveUrl()}.`
668
+ });
669
+ const url = backend.remote?.url;
670
+ const graphqlRef = resolved ? void 0 : endpointsGraphqlRef(url);
671
+ if (graphqlRef) ctx.addIssue({
672
+ code: "custom",
673
+ path: ["remote", "url"],
674
+ 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)}.`
675
+ });
676
+ if (resolved && typeof url === "string" && !switchboardOfDrive(url)) ctx.addIssue({
677
+ code: "custom",
678
+ path: ["remote", "url"],
679
+ message: `remote.url must be a switchboard drive address (<switchboard>/d/<slug>), not ${url}: sync needs the drive. Use ${useDriveUrl()}.`
680
+ });
681
+ const store = backend.storage;
682
+ const storeDir = store?.kind === "path" ? store.dataDir : void 0;
683
+ const readModel = backend.readModel?.url;
684
+ if (typeof storeDir === "string" && readModel && samePath(storeDir, readModel)) ctx.addIssue({
685
+ code: "custom",
686
+ path: ["readModel", "url"],
687
+ message: `readModel.url must not be the reactor's storage dir (${readModel}): two PGlite instances on one data dir corrupt it. Omit readModel.url to get the classic <root>/.ph/read-storage next to the reactor store.`
688
+ });
689
+ });
690
+ const reactorSchema = strictObject({
691
+ backends: record(string(), reactorBackendSchema).optional(),
692
+ placement: strictObject({
693
+ primary: string().optional(),
694
+ /** Declared drive slug → backend name. A local backend keeps a
695
+ * synced copy; the drive's own remote backend opens it there with
696
+ * no copy. An unlisted drive keeps a synced copy. */
697
+ drives: record(string().min(1), string().min(1)).optional()
698
+ }).optional(),
699
+ protocol: reactorProtocolSchema.optional(),
700
+ /** DEPRECATED (dies in R2): workflows become a listed plugin. */
701
+ workflows: boolean().optional(),
702
+ renown: strictObject({
703
+ url: string().optional(),
704
+ networkId: string().optional(),
705
+ chainId: number().int().optional()
706
+ }).optional(),
707
+ namespace: string().min(1).optional(),
708
+ drives: tokenField.any(array(buildDriveDeclarationSchema(tokenField.any))).optional()
709
+ }).superRefine((reactor, ctx) => {
710
+ const backends = reactor.backends ?? {};
711
+ for (const [slug, name] of Object.entries(reactor.placement?.drives ?? {})) {
712
+ if (Object.hasOwn(backends, name)) continue;
713
+ ctx.addIssue({
714
+ code: "custom",
715
+ path: [
716
+ "placement",
717
+ "drives",
718
+ slug
719
+ ],
720
+ message: `placement.drives.${slug} names backend "${name}", which is not in backends (${Object.keys(backends).join(", ") || "none"}).`
721
+ });
722
+ }
723
+ if (resolved) refineResolvedReactor(reactor, ctx);
724
+ });
725
+ /** Common runner options; runner modules extend it with their own. */
726
+ const runnerBaseSchema = looseObject({
727
+ module: string().min(1),
728
+ defaultVerb: string().min(1).optional(),
729
+ port: number().int().positive().optional(),
730
+ /** Bind address; each runner documents its default. */
731
+ host: string().min(1).optional(),
732
+ /** THE COMPOSITION: plugin entries; presence is activation. */
733
+ plugins: array(pluginEntrySchema).optional()
734
+ });
735
+ /** A compound member wrapper. Sections are FULL STATEMENTS except `runner`,
736
+ * which key-merges over the member's own. Plugins live in `runner.plugins`
737
+ * (as on a standalone host); there is no wrapper-level `plugins`. */
738
+ const childWrapperSchema = strictObject({
739
+ host: string().min(1),
740
+ runner: runnerBaseSchema.partial().extend({ port: number().int().min(0).max(65535).optional() }).optional(),
741
+ config: looseObject({}).optional(),
742
+ reactor: reactorSchema.optional()
743
+ });
744
+ const childrenSchema = record(string(), childWrapperSchema);
745
+ return {
746
+ reactorBackendSchema,
747
+ reactorSchema,
748
+ runnerBaseSchema,
749
+ childWrapperSchema,
750
+ childrenSchema,
751
+ reactorHostSchema: strictObject({
752
+ name: hostNameSchema,
753
+ runner: runnerBaseSchema,
754
+ config: looseObject({}).optional(),
755
+ profile: profileSchema.optional(),
756
+ reactor: reactorSchema.optional()
757
+ }),
758
+ compoundHostSchema: strictObject({
759
+ name: hostNameSchema,
760
+ runner: runnerBaseSchema,
761
+ children: childrenSchema,
762
+ config: looseObject({}).optional(),
763
+ profile: profileSchema.optional()
764
+ }),
765
+ /** This set's field wrapper, for a runner's OWN token-able fields inside
766
+ * `defineHostSchemas`: declared, `T | Token` in and `T` out; resolved,
767
+ * `T` only. Both modes share one static type. */
768
+ tokenable: tokenField.any,
769
+ /** As `tokenable`, but the only token accepted is `$env`. */
770
+ envTokenable: tokenField.env
771
+ };
772
+ }
773
+ /** The host schema set in declared ("allow": token-able fields take tokens)
774
+ * or resolved ("forbid") form. */
775
+ function makeHostSchemas(options) {
776
+ return buildHostSchemas(options.tokens === "allow" ? ALLOW_TOKENS : FORBID_TOKENS);
777
+ }
778
+ /** Adds the host-level placement key check to a runner's declared schema. */
779
+ function withPlacementKeys(schema) {
780
+ if (!(schema instanceof ZodType)) return schema;
781
+ return schema.superRefine((host, ctx) => {
782
+ if (typeof host === "object" && host !== null && "reactor" in host) refineDeclaredPlacementKeys(host, ctx);
783
+ });
784
+ }
785
+ /**
786
+ * One runner definition, two schemas (3.5): `build` runs over the DECLARED
787
+ * set (tokens allowed; its z.input types host files) and the RESOLVED set
788
+ * (no tokens; `validateHost` checks it before the verb). Export both, type
789
+ * the host as `z.input<typeof declaredHostSchema>`, refine last inside the
790
+ * builder (zod can't extend a refined object), and wrap the runner's own
791
+ * token-able fields with `s.tokenable` / `s.envTokenable`.
792
+ */
793
+ function defineHostSchemas(build) {
794
+ return {
795
+ declaredHostSchema: withPlacementKeys(build(declaredSchemas)),
796
+ hostSchema: build(resolvedSchemas)
797
+ };
798
+ }
799
+ const declaredSchemas = makeHostSchemas({ tokens: "allow" });
800
+ const resolvedSchemas = makeHostSchemas({ tokens: "forbid" });
801
+ const declaredHostSchemas = declaredSchemas;
802
+ resolvedSchemas.reactorBackendSchema;
803
+ resolvedSchemas.reactorSchema;
804
+ resolvedSchemas.runnerBaseSchema;
805
+ resolvedSchemas.childWrapperSchema;
806
+ resolvedSchemas.childrenSchema;
807
+ resolvedSchemas.reactorHostSchema;
808
+ resolvedSchemas.compoundHostSchema;
809
+ /** The generic compound runner's host: the base with its wiring config. */
810
+ const genericCompound = defineHostSchemas((s) => s.compoundHostSchema.extend({ config: compoundWiringSchema.optional() }).superRefine(refineStartOrder));
811
+ genericCompound.hostSchema;
812
+ genericCompound.declaredHostSchema;
813
+ function isPlainObject(value) {
814
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
815
+ const proto = Object.getPrototypeOf(value);
816
+ return proto === Object.prototype || proto === null;
817
+ }
818
+ /** `a.b[2].c` (or `<root>`). */
819
+ function formatPath(path) {
820
+ let out = "";
821
+ for (const segment of path) if (typeof segment === "number") out += `[${segment}]`;
822
+ else out += out ? `.${segment}` : segment;
823
+ return out || "<root>";
824
+ }
825
+ /** Is this object a `$$` escape (`{ $$: literal }`)? */
826
+ function isEscape(value) {
827
+ const keys = Object.keys(value);
828
+ return keys.length === 1 && keys[0] === TOKEN_ESCAPE_KEY;
829
+ }
830
+ /** Every token in `value`, in document order. `$concat` parts and `$map`
831
+ * operands (`over`, then the `to` template) are visited: they may hold tokens
832
+ * themselves. Each site carries the `$map` scopes it sits in. A `$$` escape
833
+ * hides its operand. */
834
+ function collectTokenSites(value) {
835
+ const sites = [];
836
+ visit(value, [], "root", [], sites);
837
+ return sites;
838
+ }
839
+ function visit(value, path, position, scopes, sites) {
840
+ const key = tokenKeyOf(value);
841
+ if (key && isPlainObject(value)) {
842
+ sites.push({
843
+ path,
844
+ key,
845
+ token: value,
846
+ position,
847
+ scopes
848
+ });
849
+ const operand = value[key];
850
+ if (key === "$concat" && Array.isArray(operand)) operand.forEach((part, index) => visit(part, [
851
+ ...path,
852
+ "$concat",
853
+ index
854
+ ], "concat", scopes, sites));
855
+ if (key === "$map" && isPlainObject(operand)) {
856
+ const at = [...path, "$map"];
857
+ if ("over" in operand) visit(operand.over, [...at, "over"], "over", scopes, sites);
858
+ if ("to" in operand) {
859
+ const scope = {
860
+ path,
861
+ token: value,
862
+ ...typeof operand.as === "string" ? { as: operand.as } : {}
863
+ };
864
+ visit(operand.to, [...at, "to"], "template", [...scopes, scope], sites);
865
+ }
866
+ }
867
+ return;
868
+ }
869
+ if (Array.isArray(value)) {
870
+ value.forEach((child, index) => visit(child, [...path, index], "element", scopes, sites));
871
+ return;
872
+ }
873
+ if (!isPlainObject(value) || isEscape(value)) return;
874
+ for (const [childKey, child] of Object.entries(value)) visit(child, [...path, childKey], "property", scopes, sites);
875
+ }
876
+ /** An `$item` path as text: `url`, `drives.x`, `<element>` for `[]`. */
877
+ function pathText(path) {
878
+ if (path.length === 0) return "<element>";
879
+ return formatPath(path.filter((p) => typeof p === "string" || typeof p === "number"));
880
+ }
881
+ /** A one-line human rendering of a token, for `--explain` and messages. */
882
+ function describeToken(token) {
883
+ const key = tokenKeyOf(token);
884
+ if (!key || !isPlainObject(token)) return JSON.stringify(token);
885
+ const operand = token[key];
886
+ if (key === "$output" && isPlainObject(operand)) return `$output ${typeof operand.host === "string" ? operand.host : "?"}${typeof operand.member === "string" ? ` (member ${operand.member})` : ""} › ${Array.isArray(operand.path) ? formatPath(operand.path.filter((p) => typeof p === "string" || typeof p === "number")) : "?"}`;
887
+ if (key === "$env") {
888
+ if (typeof operand === "string") return `$env ${operand}`;
889
+ if (isPlainObject(operand) && typeof operand.name === "string") return `$env ${operand.name} (optional)`;
890
+ }
891
+ if (key === "$item") {
892
+ const named = isPlainObject(operand) ? operand : void 0;
893
+ const raw = named ? named.path : operand;
894
+ const path = Array.isArray(raw) ? pathText(raw) : "?";
895
+ return `$item${named && typeof named.as === "string" ? `(${named.as})` : ""} ${path}`;
896
+ }
897
+ if (key === "$key") return typeof operand === "string" ? `$key(${operand})` : "$key";
898
+ if (key === "$map" && isPlainObject(operand)) {
899
+ const as = typeof operand.as === "string" ? ` as ${operand.as}` : "";
900
+ const into = operand.into === "record" ? " into record" : "";
901
+ return `$map over [${describeToken(operand.over)}]${as}${into} → ${JSON.stringify(render(operand.to))}`;
902
+ }
903
+ if (key === "$concat" && Array.isArray(operand)) return `$concat ${operand.map((part) => typeof part === "string" ? JSON.stringify(part) : typeof part === "number" ? String(part) : `[${describeToken(part)}]`).join(" + ")}`;
904
+ return `${key} ${JSON.stringify(operand)}`;
905
+ }
906
+ /** A display copy of `value` with every token replaced by `«description»`
907
+ * (for printing declared hosts, e.g. `--explain drives`). */
908
+ function renderTokens(value) {
909
+ return render(value);
910
+ }
911
+ function render(value) {
912
+ if (tokenKeyOf(value)) return `«${describeToken(value)}»`;
913
+ if (Array.isArray(value)) return value.map(render);
914
+ if (!isPlainObject(value) || isEscape(value)) return value;
915
+ const out = {};
916
+ for (const [key, child] of Object.entries(value)) out[key] = render(child);
917
+ return out;
918
+ }
919
+ /** A copy of `value` with every `$$` escape replaced by its operand (the
920
+ * literal it protects). Run after the no-token walk. */
921
+ function unwrapEscapes(value) {
922
+ return unwrap(value);
923
+ }
924
+ function unwrap(value) {
925
+ if (Array.isArray(value)) return value.map(unwrap);
926
+ if (!isPlainObject(value)) return value;
927
+ if (isEscape(value)) return structuredClone(value[TOKEN_ESCAPE_KEY]);
928
+ const out = {};
929
+ for (const [key, child] of Object.entries(value)) out[key] = unwrap(child);
930
+ return out;
931
+ }
932
+ function refOf(site) {
933
+ const operand = site.token.$output;
934
+ if (!isPlainObject(operand) || typeof operand.host !== "string") return;
935
+ return typeof operand.member === "string" ? {
936
+ host: operand.host,
937
+ member: operand.member
938
+ } : { host: operand.host };
939
+ }
940
+ function pathOf(site) {
941
+ const operand = site.token.$output;
942
+ if (!isPlainObject(operand) || !Array.isArray(operand.path)) return [];
943
+ return operand.path.filter((p) => typeof p === "string" || typeof p === "number");
944
+ }
945
+ function refKey(ref) {
946
+ return ref.member ? `${ref.host}#${ref.member}` : ref.host;
947
+ }
948
+ /** The distinct producers a host's `$output` tokens name, in document order. */
949
+ function outputRefsOf(host) {
950
+ const seen = /* @__PURE__ */ new Map();
951
+ for (const site of collectTokenSites(host)) {
952
+ if (site.key !== "$output") continue;
953
+ const ref = refOf(site);
954
+ if (ref && !seen.has(refKey(ref))) seen.set(refKey(ref), ref);
955
+ }
956
+ return [...seen.values()];
957
+ }
958
+ /** Every `$output` token with its host path and producer (for the plan and
959
+ * `--explain outputs`). */
960
+ function outputSitesOf(host) {
961
+ return collectTokenSites(host).flatMap((site) => {
962
+ if (site.key !== "$output") return [];
963
+ const ref = refOf(site);
964
+ return ref ? [{
965
+ path: formatPath(site.path),
966
+ ref,
967
+ outputPath: pathOf(site)
968
+ }] : [];
969
+ });
970
+ }
971
+ /** Every `$env` token with its host path (for `--explain outputs`). */
972
+ function envSitesOf(host) {
973
+ return collectTokenSites(host).flatMap((site) => {
974
+ if (site.key !== "$env") return [];
975
+ const operand = site.token.$env;
976
+ if (typeof operand === "string") return [{
977
+ path: formatPath(site.path),
978
+ name: operand,
979
+ optional: false
980
+ }];
981
+ if (isPlainObject(operand) && typeof operand.name === "string") return [{
982
+ path: formatPath(site.path),
983
+ name: operand.name,
984
+ optional: true
985
+ }];
986
+ return [];
987
+ });
988
+ }
989
+ /** The binding name an `$item`/`$key` site names (undefined: innermost). */
990
+ function bindingNameOf(site) {
991
+ const operand = site.token[site.key];
992
+ if (site.key === "$key") return typeof operand === "string" ? operand : void 0;
993
+ if (site.key === "$item" && isPlainObject(operand)) return typeof operand.as === "string" ? operand.as : void 0;
994
+ }
995
+ /** The enclosing `$map` an `$item`/`$key` site binds to, or why none. */
996
+ function scopeOf(site) {
997
+ const name = bindingNameOf(site);
998
+ if (site.scopes.length === 0) return { 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\`).` };
999
+ if (name === void 0) return site.scopes[site.scopes.length - 1];
1000
+ for (let i = site.scopes.length - 1; i >= 0; i--) if (site.scopes[i].as === name) return site.scopes[i];
1001
+ const named = site.scopes.flatMap((s) => s.as ? [`"${s.as}"`] : []);
1002
+ return { 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"}).` };
1003
+ }
1004
+ /** Item path of an `$item` site. */
1005
+ function itemPathOf(site) {
1006
+ const operand = site.token.$item;
1007
+ const raw = isPlainObject(operand) ? operand.path : operand;
1008
+ return Array.isArray(raw) ? raw.filter((p) => typeof p === "string" || typeof p === "number") : [];
1009
+ }
1010
+ /** Operator shapes and placement: malformed operands, `$item`/`$key`
1011
+ * outside any `$map` or naming an unknown binding, and
1012
+ * `{ $env: { name, optional: true } }` anywhere but the direct value of an
1013
+ * object property (it omits that property when unset). */
1014
+ function checkTokenSites(host) {
1015
+ const issues = [];
1016
+ for (const site of collectTokenSites(host)) {
1017
+ const path = formatPath(site.path);
1018
+ if (!tokenSchema.safeParse(site.token).success) {
1019
+ issues.push({
1020
+ path,
1021
+ 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" }.`
1022
+ });
1023
+ continue;
1024
+ }
1025
+ if (site.key === "$item" || site.key === "$key") {
1026
+ const scope = scopeOf(site);
1027
+ if ("error" in scope) issues.push({
1028
+ path,
1029
+ message: scope.error
1030
+ });
1031
+ continue;
1032
+ }
1033
+ const operand = site.token.$env;
1034
+ if (site.key === "$env" && isPlainObject(operand) && site.position !== "property") {
1035
+ const where = site.position === "concat" ? "a $concat part" : site.position === "element" ? "an array element" : site.position === "template" ? "the whole $map template" : "the whole host";
1036
+ issues.push({
1037
+ path,
1038
+ 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.`
1039
+ });
1040
+ }
1041
+ }
1042
+ return issues;
1043
+ }
1044
+ function defOf(schema) {
1045
+ if (!isPlainObjectLike(schema)) return void 0;
1046
+ const internals = schema._zod;
1047
+ if (!isPlainObjectLike(internals)) return void 0;
1048
+ const def = internals.def;
1049
+ if (!isPlainObjectLike(def) || typeof def.type !== "string") return void 0;
1050
+ return {
1051
+ ...def,
1052
+ type: def.type
1053
+ };
1054
+ }
1055
+ function isPlainObjectLike(value) {
1056
+ return (typeof value === "object" || typeof value === "function") && value !== null;
1057
+ }
1058
+ const WRAPPERS = /* @__PURE__ */ new Set([
1059
+ "optional",
1060
+ "nullable",
1061
+ "default",
1062
+ "prefault",
1063
+ "readonly",
1064
+ "nonoptional",
1065
+ "catch",
1066
+ "success"
1067
+ ]);
1068
+ /** The schema at `path` inside a zod schema (walking objects, records,
1069
+ * arrays, tuples, unions and wrappers), or why the path does not exist. */
1070
+ function schemaAtPath(schema, path) {
1071
+ let current = schema;
1072
+ for (let i = 0; i <= path.length; i++) {
1073
+ for (let guard = 0; guard < 32; guard++) {
1074
+ const def = defOf(current);
1075
+ if (!def) break;
1076
+ if (WRAPPERS.has(def.type)) current = def.innerType;
1077
+ else if (def.type === "lazy" && typeof def.getter === "function") {
1078
+ const getter = def.getter;
1079
+ current = getter();
1080
+ } else if (def.type === "pipe") {
1081
+ const out = defOf(def.out);
1082
+ current = out && out.type !== "transform" ? def.out : def.in;
1083
+ } else break;
1084
+ }
1085
+ if (i === path.length) return {
1086
+ ok: true,
1087
+ schema: current
1088
+ };
1089
+ const segment = path[i];
1090
+ const def = defOf(current);
1091
+ if (!def) return {
1092
+ ok: false,
1093
+ at: i,
1094
+ reason: "is not a schema"
1095
+ };
1096
+ switch (def.type) {
1097
+ case "any":
1098
+ case "unknown": return {
1099
+ ok: true,
1100
+ schema: current
1101
+ };
1102
+ case "object": {
1103
+ const shape = isPlainObjectLike(def.shape) ? def.shape : {};
1104
+ if (typeof segment === "string" && segment in shape) {
1105
+ current = shape[segment];
1106
+ break;
1107
+ }
1108
+ const catchall = defOf(def.catchall);
1109
+ if (catchall && catchall.type !== "never") {
1110
+ current = def.catchall;
1111
+ break;
1112
+ }
1113
+ const keys = Object.keys(shape);
1114
+ return {
1115
+ ok: false,
1116
+ at: i,
1117
+ reason: `has no key ${JSON.stringify(segment)} (keys: ${keys.join(", ") || "none"})`
1118
+ };
1119
+ }
1120
+ case "record":
1121
+ if (typeof segment !== "string") return {
1122
+ ok: false,
1123
+ at: i,
1124
+ reason: "is a record (string keys)"
1125
+ };
1126
+ current = def.valueType;
1127
+ break;
1128
+ case "array":
1129
+ if (typeof segment !== "number") return {
1130
+ ok: false,
1131
+ at: i,
1132
+ reason: "is an array (numeric index)"
1133
+ };
1134
+ current = def.element;
1135
+ break;
1136
+ case "tuple": {
1137
+ const items = Array.isArray(def.items) ? def.items : [];
1138
+ if (typeof segment !== "number" || segment >= items.length) return {
1139
+ ok: false,
1140
+ at: i,
1141
+ reason: `is a ${items.length}-tuple`
1142
+ };
1143
+ current = items[segment];
1144
+ break;
1145
+ }
1146
+ case "union": {
1147
+ const options = Array.isArray(def.options) ? def.options : [];
1148
+ for (const option of options) {
1149
+ const hit = schemaAtPath(option, path.slice(i));
1150
+ if (hit.ok) return hit;
1151
+ }
1152
+ return {
1153
+ ok: false,
1154
+ at: i,
1155
+ reason: "matches no union member"
1156
+ };
1157
+ }
1158
+ default: return {
1159
+ ok: false,
1160
+ at: i,
1161
+ reason: `is a ${def.type}, not a container`
1162
+ };
1163
+ }
1164
+ }
1165
+ return {
1166
+ ok: true,
1167
+ schema: current
1168
+ };
1169
+ }
1170
+ /** Whether the object schema at `path` names `key` in its shape (a
1171
+ * catchall does not count): what a runner's schema explicitly declares,
1172
+ * e.g. `runner.cspRegistrySync`. A union declares a key any member does. */
1173
+ function declaresKey(schema, path, key) {
1174
+ const at = schemaAtPath(schema, path);
1175
+ if (!at.ok) return false;
1176
+ const def = defOf(at.schema);
1177
+ if (def?.type === "object") return isPlainObjectLike(def.shape) && key in def.shape;
1178
+ if (def?.type === "union" && Array.isArray(def.options)) return def.options.some((option) => declaresKey(option, [], key));
1179
+ return false;
1180
+ }
1181
+ /** Whether a (property) schema admits an absent value on the OUTPUT side:
1182
+ * `.optional()` does; `.default()`/`.prefault()` fill it in, and
1183
+ * `.nonoptional()` forbids it. */
1184
+ function mayBeAbsent(schema) {
1185
+ let current = schema;
1186
+ for (let guard = 0; guard < 32; guard++) {
1187
+ const internals = isPlainObjectLike(current) ? current._zod : void 0;
1188
+ if (isPlainObjectLike(internals) && internals.optout === "optional") return true;
1189
+ const def = defOf(current);
1190
+ if (!def) return false;
1191
+ if (def.type === "optional") return true;
1192
+ if (def.type === "default" || def.type === "prefault" || def.type === "nonoptional" || !WRAPPERS.has(def.type)) return false;
1193
+ current = def.innerType;
1194
+ }
1195
+ return false;
1196
+ }
1197
+ /** Whether `key` may be absent from a value of the object schema `schema`:
1198
+ * an optional property, or (in a union) one some member makes optional or
1199
+ * lacks. A record value or an array element is never optional. */
1200
+ function optionalKeyIn(schema, key) {
1201
+ const unwrapped = schemaAtPath(schema, []);
1202
+ const def = unwrapped.ok ? defOf(unwrapped.schema) : void 0;
1203
+ if (def?.type === "object") {
1204
+ const shape = isPlainObjectLike(def.shape) ? def.shape : {};
1205
+ return key in shape && mayBeAbsent(shape[key]);
1206
+ }
1207
+ if (def?.type === "union" && Array.isArray(def.options)) return def.options.some((option) => {
1208
+ const inner = schemaAtPath(option, []);
1209
+ const optionDef = inner.ok ? defOf(inner.schema) : void 0;
1210
+ const shape = optionDef?.type === "object" && isPlainObjectLike(optionDef.shape) ? optionDef.shape : void 0;
1211
+ return shape !== void 0 && (!(key in shape) || mayBeAbsent(shape[key]));
1212
+ });
1213
+ return false;
1214
+ }
1215
+ /**
1216
+ * Whether the field `path[at]` is OPTIONAL in `schema` (a producer's
1217
+ * `outputsSchema`, or a `$map` element schema), given that `path[0..at-1]`
1218
+ * exists: the codegen'd `OutputToken<T | undefined>` / `ItemToken<T |
1219
+ * undefined>` positions, whose rendered property the resolver omits when
1220
+ * the field is absent. False for a record key, an array index, or a path
1221
+ * the schema does not describe.
1222
+ */
1223
+ function isOptionalField(schema, path, at) {
1224
+ const key = path[at];
1225
+ if (typeof key !== "string") return false;
1226
+ const parent = schemaAtPath(schema, path.slice(0, at));
1227
+ return parent.ok && optionalKeyIn(parent.schema, key);
1228
+ }
1229
+ /** The element schema of a collection schema (array element, record
1230
+ * value), or undefined when the schema does not say. */
1231
+ function elementSchemaOf(schema) {
1232
+ const collection = collectionOf(schema);
1233
+ return collection.kind === "array" || collection.kind === "record" ? collection.element : void 0;
1234
+ }
1235
+ /** The collection kind of a schema (unwrapped): array, record, unknown (no
1236
+ * check possible) or something else. */
1237
+ function collectionOf(schema) {
1238
+ const unwrapped = schemaAtPath(schema, []);
1239
+ const def = unwrapped.ok ? defOf(unwrapped.schema) : void 0;
1240
+ if (!def) return { kind: "unknown" };
1241
+ if (def.type === "array") return {
1242
+ kind: "array",
1243
+ element: def.element
1244
+ };
1245
+ if (def.type === "record") return {
1246
+ kind: "record",
1247
+ element: def.valueType
1248
+ };
1249
+ if (def.type === "object") {
1250
+ const catchall = defOf(def.catchall);
1251
+ if (catchall && catchall.type !== "never") {
1252
+ const shape = isPlainObjectLike(def.shape) ? def.shape : {};
1253
+ return Object.keys(shape).length === 0 ? {
1254
+ kind: "record",
1255
+ element: def.catchall
1256
+ } : {
1257
+ kind: "record",
1258
+ element: void 0
1259
+ };
1260
+ }
1261
+ }
1262
+ if (def.type === "tuple") return {
1263
+ kind: "array",
1264
+ element: void 0
1265
+ };
1266
+ if (def.type === "any" || def.type === "unknown" || def.type === "union") return { kind: "unknown" };
1267
+ return {
1268
+ kind: "other",
1269
+ type: def.type
1270
+ };
1271
+ }
1272
+ /** Every `$output` token's producer exists and its path is valid against
1273
+ * the producer's `outputsSchema`; every `$map`'s `over` is a collection
1274
+ * there (a record under `into: "record"`), and every `$item` path exists
1275
+ * in the element schema of the map it binds. */
1276
+ function checkOutputPaths(host, outputsSchemaOf) {
1277
+ const issues = [];
1278
+ const elements = /* @__PURE__ */ new Map();
1279
+ const elementOf = (scope) => "error" in scope ? void 0 : elements.get(scope.token);
1280
+ for (const site of collectTokenSites(host)) {
1281
+ if (!tokenSchema.safeParse(site.token).success) continue;
1282
+ if (site.key === "$map") {
1283
+ elements.set(site.token, checkMap(site, outputsSchemaOf, elementOf, issues));
1284
+ continue;
1285
+ }
1286
+ if (site.key === "$item") {
1287
+ const scope = scopeOf(site);
1288
+ const element = elementOf(scope);
1289
+ if (!element || element.element === void 0 || "error" in scope) continue;
1290
+ const itemPath = itemPathOf(site);
1291
+ const hit = schemaAtPath(element.element, itemPath);
1292
+ if (!hit.ok) {
1293
+ const parent = itemPath.slice(0, hit.at);
1294
+ issues.push({
1295
+ path: formatPath(site.path),
1296
+ 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}).`
1297
+ });
1298
+ }
1299
+ continue;
1300
+ }
1301
+ if (site.key !== "$output") continue;
1302
+ const ref = refOf(site);
1303
+ if (!ref) continue;
1304
+ const path = formatPath(site.path);
1305
+ const lookup = outputsSchemaOf(ref);
1306
+ if ("error" in lookup) {
1307
+ issues.push({
1308
+ path,
1309
+ message: lookup.error
1310
+ });
1311
+ continue;
1312
+ }
1313
+ const outputPath = pathOf(site);
1314
+ const hit = schemaAtPath(lookup.schema, outputPath);
1315
+ if (!hit.ok) {
1316
+ const parent = outputPath.slice(0, hit.at);
1317
+ const where = parent.length ? `outputs.${formatPath(parent)}` : "the outputs";
1318
+ issues.push({
1319
+ path,
1320
+ message: `${describeToken(site.token)}: ${where} ${hit.reason} in the outputsSchema of ${lookup.label}.`
1321
+ });
1322
+ }
1323
+ }
1324
+ return issues;
1325
+ }
1326
+ /** A `$map`'s `over` against its schema: a collection (a record under
1327
+ * `into: "record"`). Returns the element schema for the map's `$item`s. */
1328
+ function checkMap(site, outputsSchemaOf, elementOf, issues) {
1329
+ const operand = site.token.$map;
1330
+ if (!isPlainObject(operand)) return void 0;
1331
+ const over = operand.over;
1332
+ const into = operand.into === "record";
1333
+ let schema;
1334
+ let label;
1335
+ if (isPlainObject(over) && "$output" in over) {
1336
+ const overSite = {
1337
+ ...site,
1338
+ key: "$output",
1339
+ token: over
1340
+ };
1341
+ const ref = refOf(overSite);
1342
+ if (!ref) return void 0;
1343
+ const lookup = outputsSchemaOf(ref);
1344
+ if ("error" in lookup) return void 0;
1345
+ const hit = schemaAtPath(lookup.schema, pathOf(overSite));
1346
+ if (!hit.ok) return void 0;
1347
+ schema = hit.schema;
1348
+ label = `${describeToken(over)} in the outputsSchema of ${lookup.label}`;
1349
+ } else if (isPlainObject(over) && "$item" in over) {
1350
+ const overSite = {
1351
+ ...site,
1352
+ key: "$item",
1353
+ token: over
1354
+ };
1355
+ const outer = elementOf(scopeOf(overSite));
1356
+ if (!outer || outer.element === void 0) return void 0;
1357
+ const hit = schemaAtPath(outer.element, itemPathOf(overSite));
1358
+ if (!hit.ok) return void 0;
1359
+ schema = hit.schema;
1360
+ label = `${describeToken(over)} (element of ${outer.label})`;
1361
+ } else return;
1362
+ const path = formatPath(site.path);
1363
+ const collection = collectionOf(schema);
1364
+ if (collection.kind === "unknown") return void 0;
1365
+ if (collection.kind === "other") {
1366
+ issues.push({
1367
+ path,
1368
+ message: `$map over ${label} is a ${collection.type}, not an array or a record; a $map iterates a collection.`
1369
+ });
1370
+ return;
1371
+ }
1372
+ if (into && collection.kind === "array") {
1373
+ issues.push({
1374
+ path,
1375
+ 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.`
1376
+ });
1377
+ return;
1378
+ }
1379
+ return {
1380
+ element: collection.element,
1381
+ label
1382
+ };
1383
+ }
1384
+ function outputToken(host, path, member) {
1385
+ return `{ $output: { host: "${host}"${member ? `, member: "${member}"` : ""}, path: [${path.map((p) => JSON.stringify(p)).join(", ")}] } }`;
1386
+ }
1387
+ function isDriveReference(value) {
1388
+ if (!isPlainObject(value)) return false;
1389
+ const keys = Object.keys(value).sort();
1390
+ return keys.length === 2 && keys[0] === "from" && keys[1] === "slug" && typeof value.from === "string" && typeof value.slug === "string";
1391
+ }
1392
+ function checkReactor(reactor, base, found) {
1393
+ if (!isPlainObject(reactor) || !isPlainObject(reactor.backends)) return;
1394
+ for (const [name, backend] of Object.entries(reactor.backends)) {
1395
+ if (!isPlainObject(backend) || !isPlainObject(backend.remote)) continue;
1396
+ const host = backend.remote.host;
1397
+ if (host === void 0) continue;
1398
+ const producer = typeof host === "string" ? host : "switchboard";
1399
+ found.push({
1400
+ path: `${base}reactor.backends.${name}.remote.host`,
1401
+ 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, [
1402
+ "drives",
1403
+ "<slug>",
1404
+ "url"
1405
+ ])} }.`
1406
+ });
1407
+ }
1408
+ }
1409
+ function checkPlugins(runner, base, memberHosts, found) {
1410
+ if (!isPlainObject(runner) || !Array.isArray(runner.plugins)) return;
1411
+ runner.plugins.forEach((entry, index) => {
1412
+ if (!isPlainObject(entry) || !isPlainObject(entry.config)) return;
1413
+ for (const [key, value] of Object.entries(entry.config)) {
1414
+ if (!isDriveReference(value)) continue;
1415
+ const host = memberHosts[value.from] ?? value.from;
1416
+ const member = memberHosts[value.from] ? value.from : void 0;
1417
+ found.push({
1418
+ path: `${base}runner.plugins[${index}].config.${key}`,
1419
+ message: `${key}: { from, slug } was removed; use ${host}.drives.${value.slug}.url from ../${host}/outputs.js, or ${outputToken(host, [
1420
+ "drives",
1421
+ value.slug,
1422
+ "url"
1423
+ ])}${member ? ` (add member: "${member}" if two members run host "${host}")` : ""}.`
1424
+ });
1425
+ }
1426
+ });
1427
+ }
1428
+ /** Every removed form in a host file (reactor or compound), in document
1429
+ * order. Compound wrappers are checked too. */
1430
+ function findRemovedForms(host) {
1431
+ const found = [];
1432
+ if (!isPlainObject(host)) return found;
1433
+ const children = isPlainObject(host.children) ? host.children : void 0;
1434
+ const memberHosts = {};
1435
+ for (const [key, wrapper] of Object.entries(children ?? {})) if (isPlainObject(wrapper) && typeof wrapper.host === "string") memberHosts[key] = wrapper.host;
1436
+ checkReactor(host.reactor, "", found);
1437
+ checkPlugins(host.runner, "", memberHosts, found);
1438
+ for (const [key, wrapper] of Object.entries(children ?? {})) {
1439
+ if (!isPlainObject(wrapper)) continue;
1440
+ checkReactor(wrapper.reactor, `children.${key}.`, found);
1441
+ checkPlugins(wrapper.runner, `children.${key}.`, memberHosts, found);
1442
+ }
1443
+ if (children && isPlainObject(host.config)) for (const key of ["projectDrivesIntoConnect", "drivesPublicBase"]) {
1444
+ if (host.config[key] === void 0) continue;
1445
+ found.push({
1446
+ path: `config.${key}`,
1447
+ 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", [
1448
+ "drives",
1449
+ "<slug>",
1450
+ "url"
1451
+ ])} } }].`
1452
+ });
1453
+ }
1454
+ return found;
1455
+ }
1456
+ /** The always-resolvable `$env` names (also the `"${name}"` sugar). */
1457
+ const BUILTIN_ENV_NAMES = ["userData", "projectRoot"];
1458
+ function isBuiltinEnvName(name) {
1459
+ return BUILTIN_ENV_NAMES.includes(name);
1460
+ }
1461
+ const BUILTIN = new RegExp(`\\$\\{(${BUILTIN_ENV_NAMES.join("|")})\\}`, "g");
1462
+ function substitute(text, env) {
1463
+ return text.replace(BUILTIN, (match, name) => env[name] ?? match);
1464
+ }
1465
+ /** Deep-substitute the built-ins that `env` provides in every string; an
1466
+ * absent built-in is left as written. The input is never mutated. */
1467
+ function substituteBuiltinEnv(value, env) {
1468
+ return substituteValue(value, env);
1469
+ }
1470
+ function substituteValue(value, env) {
1471
+ if (typeof value === "string") return substitute(value, env);
1472
+ if (Array.isArray(value)) return value.map((v) => substituteValue(v, env));
1473
+ if (value !== null && typeof value === "object") {
1474
+ const out = {};
1475
+ for (const [k, v] of Object.entries(value)) out[k] = substituteValue(v, env);
1476
+ return out;
1477
+ }
1478
+ return value;
1479
+ }
1480
+ /**
1481
+ * The dependency plan (pipeline step 4): which compound member consumes
1482
+ * which member's outputs, and the start order that follows. Producers start
1483
+ * before consumers; `config.startOrder` is optional and, when given, must
1484
+ * agree with the tokens. Cycles fail. Pure.
1485
+ */
1486
+ var PlanError = class extends Error {
1487
+ constructor(message) {
1488
+ super(message);
1489
+ this.name = "PlanError";
1490
+ }
1491
+ };
1492
+ /** The member a ref names: the unique member running `ref.host`, or the
1493
+ * member `ref.member` when given (it must run `ref.host`). */
1494
+ function memberForRef(ref, members) {
1495
+ if (ref.member !== void 0) {
1496
+ const named = members.find((m) => m.key === ref.member);
1497
+ if (!named) return { error: `names member "${ref.member}", which this compound does not declare (members: ${members.map((m) => m.key).join(", ")}).` };
1498
+ if (named.host !== ref.host) return { error: `names member "${ref.member}" of host "${ref.host}", but that member runs host "${named.host}".` };
1499
+ return { key: named.key };
1500
+ }
1501
+ const running = members.filter((m) => m.host === ref.host);
1502
+ if (running.length === 1) return { key: running[0].key };
1503
+ if (running.length === 0) return { error: `names host "${ref.host}", which no member of this compound runs (members run: ${[...new Set(members.map((m) => m.host))].join(", ")}).` };
1504
+ return { error: `names host "${ref.host}", which members ${running.map((m) => `"${m.key}"`).join(" and ")} both run; add member: "<key>" to pick one.` };
1505
+ }
1506
+ function edgesOf(members) {
1507
+ const edges = [];
1508
+ const problems = [];
1509
+ for (const member of members) {
1510
+ const seen = /* @__PURE__ */ new Set();
1511
+ for (const { ref, path } of member.refs) {
1512
+ const target = memberForRef(ref, members);
1513
+ if ("error" in target) {
1514
+ problems.push(`${member.key}: ${path} ${target.error}`);
1515
+ continue;
1516
+ }
1517
+ if (target.key === member.key) {
1518
+ problems.push(`${member.key}: ${path} reads ${refKey(ref)}'s outputs, which is this member itself.`);
1519
+ continue;
1520
+ }
1521
+ if (seen.has(target.key)) continue;
1522
+ seen.add(target.key);
1523
+ edges.push({
1524
+ consumer: member.key,
1525
+ producer: target.key,
1526
+ path
1527
+ });
1528
+ }
1529
+ }
1530
+ if (problems.length > 0) throw new PlanError(problems.join("\n"));
1531
+ return edges;
1532
+ }
1533
+ /** Declared start order: the named members first, then the rest in
1534
+ * declaration order. */
1535
+ function declaredOrder(members, startOrder) {
1536
+ const keys = members.map((m) => m.key);
1537
+ const named = [...new Set(startOrder)].filter((k) => keys.includes(k));
1538
+ return [...named, ...keys.filter((k) => !named.includes(k))];
1539
+ }
1540
+ function planCompound(members, startOrder) {
1541
+ const edges = edgesOf(members);
1542
+ if (startOrder) {
1543
+ const order = declaredOrder(members, startOrder);
1544
+ const index = new Map(order.map((k, i) => [k, i]));
1545
+ const bad = edges.filter((e) => (index.get(e.producer) ?? 0) > (index.get(e.consumer) ?? 0));
1546
+ if (bad.length > 0) throw new PlanError(bad.map((e) => `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).`).join("\n"));
1547
+ return {
1548
+ order,
1549
+ edges,
1550
+ source: "startOrder"
1551
+ };
1552
+ }
1553
+ const pending = new Map(members.map((m) => [m.key, /* @__PURE__ */ new Set()]));
1554
+ for (const e of edges) pending.get(e.consumer)?.add(e.producer);
1555
+ const order = [];
1556
+ while (order.length < members.length) {
1557
+ const next = members.find((m) => !order.includes(m.key) && pending.get(m.key)?.size === 0);
1558
+ if (!next) {
1559
+ const stuck = members.filter((m) => !order.includes(m.key));
1560
+ throw new PlanError(`output tokens form a cycle between ${stuck.map((m) => `"${m.key}"`).join(", ")}: ${edges.filter((e) => stuck.some((m) => m.key === e.consumer) && stuck.some((m) => m.key === e.producer)).map((e) => `${e.consumer} (${e.path}) needs ${e.producer}`).join("; ")}.`);
1561
+ }
1562
+ order.push(next.key);
1563
+ for (const set of pending.values()) set.delete(next.key);
1564
+ }
1565
+ return {
1566
+ order,
1567
+ edges,
1568
+ source: "tokens"
1569
+ };
1570
+ }
1571
+ var TokenResolutionError = class extends Error {
1572
+ /** The host path that failed and the reason, without the file prefix. */
1573
+ detail;
1574
+ constructor(message, detail) {
1575
+ super(message);
1576
+ this.name = "TokenResolutionError";
1577
+ if (detail) this.detail = detail;
1578
+ }
1579
+ };
1580
+ /** Why a required `$env` cannot resolve. */
1581
+ function unsetEnvMessage(name) {
1582
+ 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).`;
1583
+ }
1584
+ /** A resolved `{ $env: { name, optional: true } }` whose variable is unset,
1585
+ * or an `$output`/`$item` reading an absent optional field: its enclosing
1586
+ * property is omitted. */
1587
+ const OMIT = Symbol("omit");
1588
+ /** `reactor.drives["workflows"]` (or `…[2]` for an array element). */
1589
+ function elementText(binding) {
1590
+ const key = typeof binding.key === "number" ? `[${binding.key}]` : `[${JSON.stringify(binding.key)}]`;
1591
+ return `${formatPath(binding.path)}${key}`;
1592
+ }
1593
+ /** Provenance of `$map`-rendered arrays: element index → the input key
1594
+ * (record key, or array index) it was rendered from. Lets resolved
1595
+ * validation name the element key, not just the result index. */
1596
+ const renderedKeys = /* @__PURE__ */ new WeakMap();
1597
+ /**
1598
+ * The `$map` elements an issue path (from resolved validation of a resolved
1599
+ * host) passes through, as text: `$map element "workflows"`. Undefined when
1600
+ * the path crosses no `$map`-rendered array. Walk the SAME object
1601
+ * `resolveHostOutputs` returned (provenance is by identity).
1602
+ */
1603
+ function describeMapElements(host, path) {
1604
+ const found = [];
1605
+ let current = host;
1606
+ for (const segment of path) if (Array.isArray(current) && typeof segment === "number") {
1607
+ const key = renderedKeys.get(current)?.[segment];
1608
+ if (key !== void 0) found.push(`$map element ${typeof key === "number" ? `[${key}]` : JSON.stringify(key)}`);
1609
+ current = current[segment];
1610
+ } else if (isPlainObject(current) && typeof segment === "string") current = current[segment];
1611
+ else break;
1612
+ return found.length ? found.join(" › ") : void 0;
1613
+ }
1614
+ /** A deep copy of a resolved (JSON-shaped) value that keeps the `$map`
1615
+ * provenance of its rendered arrays (structuredClone would drop it). */
1616
+ function cloneWithProvenance(value) {
1617
+ if (Array.isArray(value)) {
1618
+ const copy = value.map(cloneWithProvenance);
1619
+ const keys = renderedKeys.get(value);
1620
+ if (keys) renderedKeys.set(copy, keys);
1621
+ return copy;
1622
+ }
1623
+ if (isPlainObject(value)) {
1624
+ const copy = {};
1625
+ for (const [key, child] of Object.entries(value)) copy[key] = cloneWithProvenance(child);
1626
+ return copy;
1627
+ }
1628
+ return value;
1629
+ }
1630
+ /** The value at `path` inside `root` (output data: records and arrays). */
1631
+ function walkPath(root, path) {
1632
+ let current = root;
1633
+ for (let i = 0; i < path.length; i++) {
1634
+ const segment = path[i];
1635
+ const next = Array.isArray(current) ? typeof segment === "number" ? current[segment] : void 0 : isPlainObject(current) && typeof segment === "string" ? current[segment] : void 0;
1636
+ if (next === void 0) {
1637
+ const has = isPlainObject(current) ? Object.keys(current).join(", ") || "nothing" : Array.isArray(current) ? `${current.length} elements` : JSON.stringify(current);
1638
+ return {
1639
+ ok: false,
1640
+ at: i,
1641
+ has
1642
+ };
1643
+ }
1644
+ current = next;
1645
+ }
1646
+ return {
1647
+ ok: true,
1648
+ value: current
1649
+ };
1650
+ }
1651
+ /** The schema at `path` inside `schema`, when both are known. */
1652
+ function schemaOf(schema, path) {
1653
+ if (schema === void 0) return void 0;
1654
+ const hit = schemaAtPath(schema, path);
1655
+ return hit.ok ? hit.schema : void 0;
1656
+ }
1657
+ function pathSegments(path) {
1658
+ return path.filter((p) => typeof p === "string" || typeof p === "number");
1659
+ }
1660
+ var Resolver = class {
1661
+ sources;
1662
+ self;
1663
+ deferred = [];
1664
+ /** What the last OMIT stood for, for the "nothing to omit" errors. */
1665
+ omitted = "an optional $env";
1666
+ constructor(sources, self) {
1667
+ this.sources = sources;
1668
+ this.self = self;
1669
+ }
1670
+ /** The member keys a token reads (`$output` on a member's host), when
1671
+ * resolving a compound's own fields with `deferSelf`. */
1672
+ selfRefs(token, trail) {
1673
+ if (!this.self) return [];
1674
+ const keys = /* @__PURE__ */ new Set();
1675
+ for (const site of collectTokenSites(token)) {
1676
+ const operand = site.token.$output;
1677
+ if (site.key !== "$output" || !isPlainObject(operand)) continue;
1678
+ if (typeof operand.host !== "string") continue;
1679
+ const ref = typeof operand.member === "string" ? {
1680
+ host: operand.host,
1681
+ member: operand.member
1682
+ } : { host: operand.host };
1683
+ if (this.self === "outputs") {
1684
+ keys.add(refKey(ref));
1685
+ continue;
1686
+ }
1687
+ if (!this.self.members.some((m) => m.host === ref.host)) continue;
1688
+ const target = memberForRef(ref, this.self.members);
1689
+ if ("error" in target) this.fail([...trail, ...site.path], `in a compound ${target.error}`);
1690
+ keys.add(target.key);
1691
+ }
1692
+ return [...keys];
1693
+ }
1694
+ fail(trail, message, scope = []) {
1695
+ const where = this.sources.where ? `${this.sources.where}: ` : "";
1696
+ const inside = scope.length ? ` (rendering $map element ${scope.map(elementText).join(" › ")})` : "";
1697
+ const path = formatPath(trail);
1698
+ throw new TokenResolutionError(`${where}\`${path}\` ${message}${inside}`, {
1699
+ path,
1700
+ reason: `${message}${inside}`
1701
+ });
1702
+ }
1703
+ value(value, trail, scope = []) {
1704
+ if (typeof value === "string") return this.sources.builtins ? substituteBuiltinEnv(value, this.sources.builtins) : value;
1705
+ if (Array.isArray(value)) return value.map((child, index) => {
1706
+ const out = this.value(child, [...trail, index], scope);
1707
+ if (out === OMIT) this.fail([...trail, index], `is ${this.omitted} inside an array.`, scope);
1708
+ return out;
1709
+ });
1710
+ if (!isPlainObject(value)) return value;
1711
+ if (isEscape(value)) return structuredClone(value);
1712
+ if (tokenKeyOf(value)) {
1713
+ const members = scope.length === 0 ? this.selfRefs(value, trail) : [];
1714
+ if (members.length > 0) {
1715
+ this.deferred.push({
1716
+ trail,
1717
+ token: value,
1718
+ members
1719
+ });
1720
+ return structuredClone(value);
1721
+ }
1722
+ return this.token(value, trail, scope);
1723
+ }
1724
+ const out = {};
1725
+ for (const [key, child] of Object.entries(value)) {
1726
+ if (typeof this.self === "object" && trail.length === 0 && key === "children") {
1727
+ out[key] = child;
1728
+ continue;
1729
+ }
1730
+ const resolved = this.value(child, [...trail, key], scope);
1731
+ if (resolved !== OMIT) out[key] = resolved;
1732
+ }
1733
+ return out;
1734
+ }
1735
+ token(token, trail, scope = []) {
1736
+ if (!tokenSchema.safeParse(token).success) this.fail(trail, `is a malformed token: ${JSON.stringify(token)}.`, scope);
1737
+ switch (tokenKeyOf(token)) {
1738
+ case "$output": return this.output(token, trail, scope);
1739
+ case "$env": return this.env(token.$env, trail, scope);
1740
+ case "$concat": return this.concat(token.$concat, trail, scope);
1741
+ case "$map": return this.map(token.$map, trail, scope);
1742
+ case "$item": return this.item(token.$item, trail, scope);
1743
+ case "$key": return this.key(token.$key, trail, scope);
1744
+ default: return this.fail(trail, `is not a token.`, scope);
1745
+ }
1746
+ }
1747
+ /** The binding an `$item`/`$key` names: the innermost map, or the
1748
+ * enclosing map whose `as` is `name`. */
1749
+ binding(name, operator, trail, scope) {
1750
+ if (scope.length === 0) return this.fail(trail, `uses ${operator} outside any $map; ${operator} reads the element a $map template is rendering.`);
1751
+ if (name === void 0) return scope[scope.length - 1];
1752
+ for (let i = scope.length - 1; i >= 0; i--) if (scope[i].as === name) return scope[i];
1753
+ const named = scope.flatMap((b) => b.as ? [`"${b.as}"`] : []);
1754
+ return this.fail(trail, `uses ${operator} with binding "${name}", which no enclosing $map declares (as: ${named.join(", ") || "none"}).`, scope);
1755
+ }
1756
+ map(operand, trail, scope) {
1757
+ if (!isPlainObject(operand)) return this.fail(trail, "is a malformed $map token.", scope);
1758
+ const into = operand.into === "record";
1759
+ const as = typeof operand.as === "string" ? operand.as : void 0;
1760
+ const read = this.readWithSchema(operand.over, [
1761
+ ...trail,
1762
+ "$map",
1763
+ "over"
1764
+ ], scope);
1765
+ const over = read.value;
1766
+ if (over === OMIT) return OMIT;
1767
+ const element = read.schema === void 0 ? void 0 : elementSchemaOf(read.schema);
1768
+ const render = (key, item) => {
1769
+ const inner = [...scope, {
1770
+ path: trail,
1771
+ key,
1772
+ item,
1773
+ ...as !== void 0 ? { as } : {},
1774
+ ...element !== void 0 ? { schema: element } : {}
1775
+ }];
1776
+ const at = [
1777
+ ...trail,
1778
+ "$map",
1779
+ "to"
1780
+ ];
1781
+ const out = this.value(operand.to, at, inner);
1782
+ if (out === OMIT) return this.fail(at, `is ${this.omitted} as the whole $map template; there is no property to omit.`, inner);
1783
+ return out;
1784
+ };
1785
+ if (Array.isArray(over)) {
1786
+ if (into) return this.fail(trail, `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.`, scope);
1787
+ const rendered = over.map((item, index) => render(index, item));
1788
+ renderedKeys.set(rendered, over.map((_, index) => index));
1789
+ return rendered;
1790
+ }
1791
+ if (isPlainObject(over)) {
1792
+ const keys = Object.keys(over).sort();
1793
+ if (!into) {
1794
+ const rendered = keys.map((key) => render(key, over[key]));
1795
+ renderedKeys.set(rendered, keys);
1796
+ return rendered;
1797
+ }
1798
+ const out = {};
1799
+ for (const key of keys) out[key] = render(key, over[key]);
1800
+ return out;
1801
+ }
1802
+ return this.fail(trail, `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"}.`, scope);
1803
+ }
1804
+ item(operand, trail, scope) {
1805
+ return this.readItem(operand, trail, scope).value;
1806
+ }
1807
+ /** A `$map`'s `over` with the schema describing it, when it reads a
1808
+ * schema'd `$output` (or an `$item` of a schema'd element). */
1809
+ readWithSchema(value, trail, scope) {
1810
+ const key = tokenKeyOf(value);
1811
+ if (isPlainObject(value) && (key === "$output" || key === "$item") && tokenSchema.safeParse(value).success) return key === "$output" ? this.readOutput(value, trail, scope) : this.readItem(value.$item, trail, scope);
1812
+ return { value: this.value(value, trail, scope) };
1813
+ }
1814
+ omit(what) {
1815
+ this.omitted = what;
1816
+ return { value: OMIT };
1817
+ }
1818
+ readItem(operand, trail, scope) {
1819
+ const named = isPlainObject(operand) ? operand : void 0;
1820
+ const name = named && typeof named.as === "string" ? named.as : void 0;
1821
+ const raw = named ? named.path : operand;
1822
+ const path = pathSegments(Array.isArray(raw) ? raw : []);
1823
+ const binding = this.binding(name, "$item", trail, scope);
1824
+ const hit = walkPath(binding.item, path);
1825
+ if (!hit.ok) {
1826
+ if (binding.schema !== void 0 && isOptionalField(binding.schema, path, hit.at)) return this.omit("an absent optional $item field");
1827
+ const missing = formatPath(path.slice(0, hit.at + 1));
1828
+ return this.fail(trail, `reads $item ${formatPath(path)}, but $map element ${elementText(binding)} has no ${missing} (it has: ${hit.has}).`, scope);
1829
+ }
1830
+ return {
1831
+ value: structuredClone(hit.value),
1832
+ schema: schemaOf(binding.schema, path)
1833
+ };
1834
+ }
1835
+ key(operand, trail, scope) {
1836
+ const name = typeof operand === "string" ? operand : void 0;
1837
+ return this.binding(name, "$key", trail, scope).key;
1838
+ }
1839
+ output(token, trail, scope = []) {
1840
+ return this.readOutput(token, trail, scope).value;
1841
+ }
1842
+ readOutput(token, trail, scope) {
1843
+ const operand = token.$output;
1844
+ if (!isPlainObject(operand) || typeof operand.host !== "string") return this.fail(trail, "is a malformed $output token.", scope);
1845
+ const ref = typeof operand.member === "string" ? {
1846
+ host: operand.host,
1847
+ member: operand.member
1848
+ } : { host: operand.host };
1849
+ const path = pathSegments(Array.isArray(operand.path) ? operand.path : []);
1850
+ if (!this.sources.outputs) return this.fail(trail, `reads ${describeToken(token)}, but no outputs are available here.`, scope);
1851
+ const lookup = this.sources.outputs.lookup(ref);
1852
+ if (lookup.status === "unavailable") {
1853
+ const where = this.sources.where ? `${this.sources.where}: ` : "";
1854
+ const path = formatPath(trail);
1855
+ const reason = `${lookup.message}\n (needed by \`${path}\`: ${describeToken(token)})`;
1856
+ throw new TokenResolutionError(`${where}${reason}`, {
1857
+ path,
1858
+ reason
1859
+ });
1860
+ }
1861
+ const hit = walkPath(lookup.outputs, path);
1862
+ if (!hit.ok) {
1863
+ if (lookup.schema !== void 0 && isOptionalField(lookup.schema, path, hit.at)) return this.omit("an absent optional output");
1864
+ const parent = path.slice(0, hit.at);
1865
+ const container = parent.length ? `outputs.${formatPath(parent)}` : "its outputs";
1866
+ const missing = formatPath(path.slice(0, hit.at + 1));
1867
+ return this.fail(trail, `reads ${describeToken(token)}, but host "${ref.host}" has no output at ${missing} (${container} has: ${hit.has}).`, scope);
1868
+ }
1869
+ return {
1870
+ value: structuredClone(hit.value),
1871
+ schema: schemaOf(lookup.schema, path)
1872
+ };
1873
+ }
1874
+ env(operand, trail, scope = []) {
1875
+ const optional = isPlainObject(operand);
1876
+ const name = optional ? operand.name : operand;
1877
+ if (typeof name !== "string") return this.fail(trail, "is a malformed $env token.", scope);
1878
+ const builtins = this.sources.builtins;
1879
+ if (isBuiltinEnvName(name) && builtins?.[name]) return builtins[name];
1880
+ const value = this.sources.env?.[name];
1881
+ if (value !== void 0) return value;
1882
+ if (optional) return this.omit("an optional $env").value;
1883
+ return this.fail(trail, unsetEnvMessage(name), scope);
1884
+ }
1885
+ concat(parts, trail, scope = []) {
1886
+ if (!Array.isArray(parts)) return this.fail(trail, "is a malformed $concat token.", scope);
1887
+ return parts.map((part, index) => {
1888
+ const at = [
1889
+ ...trail,
1890
+ "$concat",
1891
+ index
1892
+ ];
1893
+ const value = this.value(part, at, scope);
1894
+ if (value === OMIT) return this.fail(at, `is ${this.omitted} inside $concat.`, scope);
1895
+ if (typeof value === "string") return value;
1896
+ if (typeof value === "number") return String(value);
1897
+ return this.fail(at, `resolved to ${JSON.stringify(value)}; every $concat part must be a string or a number.`, scope);
1898
+ }).join("");
1899
+ }
1900
+ };
1901
+ function resolveHostOutputs(host, sources, options) {
1902
+ const resolver = new Resolver(sources, options?.deferSelf);
1903
+ const out = resolver.value(host, []);
1904
+ if (out === OMIT) resolver.fail([], `is ${resolver.omitted} with nothing to omit it from.`);
1905
+ const partial = out;
1906
+ if (!options) return partial;
1907
+ const sites = resolver.deferred;
1908
+ return {
1909
+ host: partial,
1910
+ deferred: sites.map((d) => ({
1911
+ path: formatPath(d.trail),
1912
+ members: d.members
1913
+ })),
1914
+ needs: [...new Set(sites.flatMap((d) => d.members))],
1915
+ finish(outputs) {
1916
+ const done = cloneWithProvenance(partial);
1917
+ const late = new Resolver({
1918
+ ...sources,
1919
+ outputs
1920
+ });
1921
+ for (const site of sites) {
1922
+ const value = late.token(site.token, site.trail);
1923
+ if (value === OMIT && typeof site.trail.at(-1) === "number") late.fail(site.trail, `is ${late.omitted} inside an array.`);
1924
+ setAt(done, site.trail, value === OMIT ? void 0 : value, value === OMIT);
1925
+ }
1926
+ return done;
1927
+ }
1928
+ };
1929
+ }
1930
+ function setAt(root, trail, value, omit) {
1931
+ let current = root;
1932
+ for (const key of trail.slice(0, -1)) if (Array.isArray(current) && typeof key === "number") current = current[key];
1933
+ else if (isPlainObject(current) && typeof key === "string") current = current[key];
1934
+ else return;
1935
+ const last = trail[trail.length - 1];
1936
+ if (Array.isArray(current) && typeof last === "number") current[last] = value;
1937
+ else if (isPlainObject(current) && typeof last === "string") {
1938
+ if (omit) delete current[last];
1939
+ else current[last] = value;
1940
+ }
1941
+ }
1942
+ /**
1943
+ * Resolves a host's `runner.module` specifier from the PROJECT's dependency
1944
+ * tree (not ph-cli's), imports it, and checks the runner-module contract:
1945
+ * `{ run, hostSchema, kind, outputsSchema?, verbs?, ...optionalVerbs }`.
1946
+ */
1947
+ var RunnerError = class extends Error {
1948
+ constructor(message, hint) {
1949
+ super(hint ? `${message}\n Hint: ${hint}` : message);
1950
+ this.name = "RunnerError";
1951
+ }
1952
+ };
1953
+ /** Whether a value is zod-shaped (has a `safeParse` function): a runner's
1954
+ * `outputsSchema`, a plugin's config schema. */
1955
+ function isSchemaLike(value) {
1956
+ return typeof value === "object" && value !== null && "safeParse" in value && typeof value.safeParse === "function";
1957
+ }
1958
+ /** The Connect runner's specifier: compounds forward `cspRegistrySync` to
1959
+ * it, and `--explain` prints its dead-config warnings. */
1960
+ const CONNECT_RUNNER = "@powerhousedao/ph-cli/runners/connect";
1961
+ /** Exports that are part of the contract but are not verbs. */
1962
+ const NON_VERB_EXPORTS = /* @__PURE__ */ new Set([
1963
+ "hostSchema",
1964
+ "declaredHostSchema",
1965
+ "outputsSchema",
1966
+ "verbs",
1967
+ "kind",
1968
+ "checkBoot",
1969
+ "default"
1970
+ ]);
1971
+ async function resolveRunnerModule(projectRoot, specifier) {
1972
+ const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
1973
+ let resolved;
1974
+ try {
1975
+ resolved = projectRequire.resolve(specifier);
1976
+ } catch {
1977
+ throw new RunnerError(`Cannot resolve runner module "${specifier}" from ${projectRoot}.`, "The runner must be a dependency of the project (install it, then retry).");
1978
+ }
1979
+ const module = await import(pathToFileURL(resolved).href);
1980
+ if (typeof module.run !== "function") throw new RunnerError(`Runner "${specifier}" does not export a \`run\` function (required verb).`);
1981
+ const hostSchema = module.hostSchema;
1982
+ if (!hostSchema || typeof hostSchema.safeParse !== "function") throw new RunnerError(`Runner "${specifier}" does not export a \`hostSchema\` — runners validate their own host shape.`);
1983
+ const declared = module.declaredHostSchema;
1984
+ if (declared !== void 0 && typeof declared.safeParse !== "function") throw new RunnerError(`Runner "${specifier}" exports a \`declaredHostSchema\` without safeParse.`);
1985
+ if (module.checkBoot !== void 0 && typeof module.checkBoot !== "function") throw new RunnerError(`Runner "${specifier}" exports a \`checkBoot\` that is not a function.`);
1986
+ const verbs = module.verbs;
1987
+ if (verbs !== void 0 && (!Array.isArray(verbs) || !verbs.every((verb) => typeof verb === "string" && typeof module[verb] === "function"))) throw new RunnerError(`Runner "${specifier}" exports \`verbs\` ${JSON.stringify(verbs)}, which must list names of exported functions.`);
1988
+ if (!runnerKindSchema.safeParse(module.kind).success) throw new RunnerError(`Runner "${specifier}" does not export a valid \`kind\` (got ${JSON.stringify(module.kind)}; expected "reactor" | "compound").`);
1989
+ return module;
1990
+ }
1991
+ /** Verbs that produce something and start nothing (`build`): no outputs, no
1992
+ * record, no lock — and no token resolution, since what they read (output
1993
+ * dirs, packages) never comes from another host's outputs. Their verb gets
1994
+ * the declared host (tokens may remain in token-able fields). */
1995
+ const ONE_SHOT_VERBS = /* @__PURE__ */ new Set(["build"]);
1996
+ function listVerbs(runner) {
1997
+ if (runner.verbs) return runner.verbs.filter((name) => typeof runner[name] === "function").toSorted();
1998
+ return Object.entries(runner).filter(([name, value]) => typeof value === "function" && !NON_VERB_EXPORTS.has(name)).map(([name]) => name).sort();
1999
+ }
2000
+ function getVerb(runner, specifier, verb) {
2001
+ const candidate = runner[verb];
2002
+ if (typeof candidate !== "function" || !listVerbs(runner).includes(verb)) throw new RunnerError(`Runner "${specifier}" does not support the verb "${verb}". Supported verbs: ${listVerbs(runner).join(", ")}.`);
2003
+ return candidate;
2004
+ }
2005
+ function isRecord$2(value) {
2006
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2007
+ }
2008
+ /** reactor XOR children, decided by the runner's declared `kind`. */
2009
+ function kindShapeIssues(kind, specifier, host) {
2010
+ if (kind === "reactor" && host.children !== void 0) return [{
2011
+ path: "children",
2012
+ message: `"${specifier}" is a reactor runner, so the host must not declare \`children\`.`,
2013
+ hint: "`children` belongs to compound hosts; a reactor host configures its own `reactor` block."
2014
+ }];
2015
+ if (kind === "compound" && host.reactor !== void 0) return [{
2016
+ path: "reactor",
2017
+ message: `"${specifier}" is a compound runner, so the host must not declare \`reactor\`.`,
2018
+ hint: "A compound's reactors are its members': configure them in the member host or a wrapper's `reactor` override."
2019
+ }];
2020
+ return [];
2021
+ }
2022
+ function assertKindShape(kind, specifier, host, file) {
2023
+ const issue = kindShapeIssues(kind, specifier, host).at(0);
2024
+ if (issue) throw new RunnerError(`${file}: ${issue.message}`, issue.hint);
2025
+ }
2026
+ /** `runner.defaultVerb` and every plugin entry's `verbs` must name verbs
2027
+ * this runner exports. */
2028
+ function knownVerbIssues(runner, specifier, host) {
2029
+ const options = host.runner;
2030
+ if (!isRecord$2(options)) return [];
2031
+ const verbs = listVerbs(runner);
2032
+ const unknownVerb = (verb) => typeof verb === "string" && !verbs.includes(verb);
2033
+ const issues = [];
2034
+ if (unknownVerb(options.defaultVerb)) issues.push({
2035
+ path: "runner.defaultVerb",
2036
+ message: `runner.defaultVerb "${options.defaultVerb}" is not a verb of "${specifier}". Supported verbs: ${verbs.join(", ")}.`
2037
+ });
2038
+ (Array.isArray(options.plugins) ? options.plugins : []).forEach((entry, index) => {
2039
+ if (!isRecord$2(entry) || !Array.isArray(entry.verbs)) return;
2040
+ const scoped = entry.verbs;
2041
+ for (const bad of scoped.filter(unknownVerb)) issues.push({
2042
+ path: `runner.plugins[${index}].verbs`,
2043
+ message: `plugin "${String(entry.module)}" is scoped to verb "${bad}", which "${specifier}" does not export. Supported verbs: ${verbs.join(", ")}.`
2044
+ });
2045
+ });
2046
+ return issues;
2047
+ }
2048
+ function formatIssues(issues) {
2049
+ return issues.map((i) => ` - ${i.path}: ${i.message}`).join("\n");
2050
+ }
2051
+ function valueAt(host, path) {
2052
+ let current = host;
2053
+ for (const key of path) if (Array.isArray(current) && typeof key === "number") current = current[key];
2054
+ else if (isRecord$2(current) && typeof key === "string") current = current[key];
2055
+ else return;
2056
+ return current;
2057
+ }
2058
+ /**
2059
+ * Resolved validation (pipeline step 6): validate a RESOLVED host against
2060
+ * its runner's `hostSchema` and return the PARSED host (what the verb
2061
+ * receives). Run `resolveHostOutputs` first; a token still present fails
2062
+ * with its path.
2063
+ */
2064
+ function validateHost(runner, specifier, host, file, options = {}) {
2065
+ return parseHost(runner, options.tokens === "allow" ? runner.declaredHostSchema ?? runner.hostSchema : runner.hostSchema, specifier, host, file, options);
2066
+ }
2067
+ /** What `validateHost` checks, as data: nothing throws. */
2068
+ function hostSchemaIssues(runner, schema, specifier, host, options = {}) {
2069
+ const issues = [];
2070
+ if (isRecord$2(host)) {
2071
+ issues.push(...kindShapeIssues(runner.kind, specifier, host));
2072
+ if (options.tokens !== "allow") {
2073
+ const token = findToken(host);
2074
+ if (token) issues.push({
2075
+ path: token.path,
2076
+ message: `\`${token.path}\` is an unresolved output token (${token.key}).`,
2077
+ hint: "Resolve the host (resolveHostOutputs) before validating it for a verb; `ph run` does this."
2078
+ });
2079
+ }
2080
+ issues.push(...knownVerbIssues(runner, specifier, host));
2081
+ }
2082
+ const result = schema.safeParse(unwrapEscapes(host));
2083
+ if (result.success) return {
2084
+ issues,
2085
+ data: result.data
2086
+ };
2087
+ return {
2088
+ issues,
2089
+ schemaIssues: result.error.issues.map((issue) => {
2090
+ const element = describeMapElements(host, issue.path);
2091
+ const dotted = (issue.path.map(String).join(".") || "<root>") + (element ? ` (${element})` : "");
2092
+ const message = issue.code !== "custom" && tokenKeyOf(valueAt(host, issue.path)) ? "this field does not take an output token (it is not token-able); spell the value literally." : issue.message;
2093
+ return {
2094
+ path: formatPath(issue.path.filter((key) => typeof key === "string" || typeof key === "number")),
2095
+ message: element ? `${message} (${element})` : message,
2096
+ printed: `${dotted}: ${message}`
2097
+ };
2098
+ })
2099
+ };
2100
+ }
2101
+ function parseHost(runner, schema, specifier, host, file, options) {
2102
+ const checked = hostSchemaIssues(runner, schema, specifier, host, options);
2103
+ const first = checked.issues.at(0);
2104
+ if (first) throw new RunnerError(`${file}: ${first.message}`, first.hint);
2105
+ if (checked.schemaIssues) throw new RunnerError(`${file} failed validation against the hostSchema of "${specifier}":\n${checked.schemaIssues.map((issue) => ` - ${issue.printed}`).join("\n") || " (no details reported)"}`);
2106
+ return checked.data;
2107
+ }
2108
+ /**
2109
+ * Declared validation (pipeline step 3): the removed cross-host forms
2110
+ * (each error names its token form), token shapes and `$env` `optional`
2111
+ * placement, `$output` paths against the producers' `outputsSchema`s, then
2112
+ * the runner's `declaredHostSchema` (tokens allowed in token-able fields).
2113
+ * Reads no environment value and needs no producer running. Throws on the
2114
+ * first failing stage; resolve, then `validateHost`, before a verb runs.
2115
+ */
2116
+ function validateDeclaredHost(runner, specifier, host, file, options = {}) {
2117
+ const removed = findRemovedForms(host);
2118
+ if (removed.length > 0) throw new RunnerError(`${file}: removed form:\n${formatIssues(removed)}`);
2119
+ const issues = checkTokenSites(host);
2120
+ if (options.outputsSchemaOf) issues.push(...checkOutputPaths(host, options.outputsSchemaOf));
2121
+ if (issues.length > 0) throw new RunnerError(`${file}: invalid output token:\n${formatIssues(issues)}`);
2122
+ if (isRecord$2(host)) assertKindShape(runner.kind, specifier, host, file);
2123
+ if (!runner.declaredHostSchema) return;
2124
+ parseHost(runner, runner.declaredHostSchema, specifier, host, file, { tokens: "allow" });
2125
+ }
2126
+ /**
2127
+ * Loads and pre-validates a `hosts/<name>/host.js` definition.
2128
+ *
2129
+ * A host file is a static PROJECTION of powerhouse.config.json: plain ESM,
2130
+ * default-exporting a data object. Three gates run before any runner sees it:
2131
+ * 1. import lint — the only legal imports are the project's
2132
+ * powerhouse.config.json, sibling `../<host>/host.js` files and sibling
2133
+ * generated `../<host>/outputs.js` token trees (host files are data, not
2134
+ * programs; `process.` is banned, environment values go through `$env`).
2135
+ * An imported outputs.js whose schema hash no longer matches its
2136
+ * producer fails here ("run `ph generate hosts`");
2137
+ * 2. static check — the exported object must survive a JSON round trip
2138
+ * (functions, undefined, class instances, Dates etc. are rejected,
2139
+ * reporting the offending path);
2140
+ * 3. shape pre-check — `name`, `runner.module`, and the reactor XOR children
2141
+ * rule. Full validation is the runner's `hostSchema` (phase 2).
2142
+ *
2143
+ * This module never exits the process — callers own error presentation.
2144
+ */
2145
+ const HOST_FILE = "host.js";
2146
+ const CONFIG_IMPORT_SUFFIX = "powerhouse.config.json";
2147
+ var HostLoadError = class extends Error {
2148
+ constructor(message, hint) {
2149
+ super(hint ? `${message}\n Hint: ${hint}` : message);
2150
+ this.name = "HostLoadError";
2151
+ }
2152
+ };
2153
+ /** A `hosts/` folder with no `<name>/host.js` inside is "empty" — the guard
2154
+ * state: callers warn loudly and fall back to legacy rather than activating
2155
+ * the new architecture off a stray `mkdir hosts`. */
2156
+ function probeHostsFolder(projectRoot) {
2157
+ const dir = path.join(projectRoot, "hosts");
2158
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) return { kind: "absent" };
2159
+ const hosts = readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && existsSync(path.join(dir, entry.name, HOST_FILE))).map((entry) => entry.name).sort();
2160
+ return hosts.length === 0 ? {
2161
+ kind: "empty",
2162
+ dir
2163
+ } : {
2164
+ kind: "present",
2165
+ dir,
2166
+ hosts
2167
+ };
2168
+ }
2169
+ /** Sibling imports: `../<host>/host.js` — source material for derived
2170
+ * compositions (full-inclusion wrappers compute over them with plain JS) —
2171
+ * and `../<host>/outputs.js`, the generated `$output` token tree. */
2172
+ const SIBLING_IMPORT = /^\.\.\/([A-Za-z0-9_-]+)\/(host\.js|outputs\.js)$/;
2173
+ /** The generated per-host token tree (`ph generate hosts`). */
2174
+ const OUTPUTS_FILE = "outputs.js";
2175
+ const GENERATE_HINT = "Run `ph generate hosts` to (re)generate hosts/<name>/outputs.js from the producer's runner outputsSchema and declared drives.";
2176
+ /**
2177
+ * One pass over JS source that blanks every comment and, with
2178
+ * `literals: "blank"`, the CONTENTS of string literals and template-literal
2179
+ * text (quotes, backticks and `${`/`}` kept). A template's `${…}` holes are
2180
+ * code: they are scanned like the rest (strings, nested templates and braces
2181
+ * inside them included). Every newline survives, so line-anchored checks and
2182
+ * line numbers still match the original source. Regex literals are not
2183
+ * recognised (host files are data; a regex is not one).
2184
+ */
2185
+ function scanSource(source, literals) {
2186
+ const blank = (text) => text.replace(/[^\n]/g, " ");
2187
+ const literal = (text) => literals === "blank" ? blank(text) : text;
2188
+ let out = "";
2189
+ let i = 0;
2190
+ const holes = [];
2191
+ /** Template text from `i` (just after a backtick or a hole's `}`) up to
2192
+ * and including its closing backtick, or up to and including the next
2193
+ * `${` (pushing a hole). */
2194
+ const templateText = () => {
2195
+ let j = i;
2196
+ while (j < source.length) {
2197
+ const ch = source[j];
2198
+ if (ch === "\\") {
2199
+ j += 2;
2200
+ continue;
2201
+ }
2202
+ if (ch === "`") break;
2203
+ if (ch === "$" && source[j + 1] === "{") break;
2204
+ j++;
2205
+ }
2206
+ out += literal(source.slice(i, Math.min(j, source.length)));
2207
+ if (j >= source.length) i = source.length;
2208
+ else if (source[j] === "`") {
2209
+ out += "`";
2210
+ i = j + 1;
2211
+ } else {
2212
+ out += "${";
2213
+ holes.push(0);
2214
+ i = j + 2;
2215
+ }
2216
+ };
2217
+ while (i < source.length) {
2218
+ const ch = source[i];
2219
+ const next = source[i + 1];
2220
+ if (ch === "/" && next === "/") {
2221
+ const end = source.indexOf("\n", i);
2222
+ const stop = end === -1 ? source.length : end;
2223
+ out += blank(source.slice(i, stop));
2224
+ i = stop;
2225
+ continue;
2226
+ }
2227
+ if (ch === "/" && next === "*") {
2228
+ const end = source.indexOf("*/", i + 2);
2229
+ const stop = end === -1 ? source.length : end + 2;
2230
+ out += blank(source.slice(i, stop));
2231
+ i = stop;
2232
+ continue;
2233
+ }
2234
+ if (ch === "\"" || ch === "'") {
2235
+ let j = i + 1;
2236
+ while (j < source.length && source[j] !== ch && source[j] !== "\n") j += source[j] === "\\" ? 2 : 1;
2237
+ const close = source[j] === ch ? ch : "";
2238
+ out += ch + literal(source.slice(i + 1, Math.min(j, source.length)));
2239
+ out += close;
2240
+ i = close ? j + 1 : j;
2241
+ continue;
2242
+ }
2243
+ if (ch === "`") {
2244
+ out += "`";
2245
+ i++;
2246
+ templateText();
2247
+ continue;
2248
+ }
2249
+ if (holes.length > 0 && ch === "{") holes[holes.length - 1]++;
2250
+ if (holes.length > 0 && ch === "}") {
2251
+ if (holes[holes.length - 1] === 0) {
2252
+ holes.pop();
2253
+ out += "}";
2254
+ i++;
2255
+ templateText();
2256
+ continue;
2257
+ }
2258
+ holes[holes.length - 1]--;
2259
+ }
2260
+ out += ch;
2261
+ i++;
2262
+ }
2263
+ return out;
2264
+ }
2265
+ /** Blank out `//` and block comments, keeping string and template literals
2266
+ * (URLs contain `//`) and every newline, so line-anchored checks still see
2267
+ * the code's own lines. A JSDoc `import("…")` type is a comment, not code. */
2268
+ function stripComments(source) {
2269
+ return scanSource(source, "keep");
2270
+ }
2271
+ /** Blank out comments and the contents of string literals and
2272
+ * template-literal text, so a word inside a string (a URL, a description,
2273
+ * an apostrophe in template text) is neither mistaken for code nor able to
2274
+ * hide code. Template `${…}` holes are code and are kept. */
2275
+ function blankLiterals(source) {
2276
+ return scanSource(source, "blank");
2277
+ }
2278
+ const PROCESS_ACCESS = /(?<![.\w$])process\s*(?:\?\.|\.|\[)/;
2279
+ /** Host files and generated outputs.js are data: reading the environment
2280
+ * through `process.` is banned (typed-host-configs decision 9). Environment
2281
+ * values go through `$env`, which resolves at start in the resolving
2282
+ * process. Comments are already stripped, so a mention there is fine. */
2283
+ function rejectProcessAccess(source, file) {
2284
+ const match = PROCESS_ACCESS.exec(blankLiterals(source));
2285
+ if (!match) return;
2286
+ const line = source.slice(0, match.index).split("\n").length;
2287
+ throw new HostLoadError(`${file}:${line} reads \`process.\` — host files cannot read the environment directly.`, "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.");
2288
+ }
2289
+ /** Lints a host file and returns what it imports. Rejects every import
2290
+ * except the project's powerhouse.config.json, SIBLING host files (R1:
2291
+ * derived compositions) and sibling generated outputs.js token trees; any
2292
+ * dynamic `import(...)` or `require(...)`; and any `process.` access.
2293
+ * Source-level enforcement: the JSON round trip below is the hard gate; this
2294
+ * one produces the better error. */
2295
+ function scanHostImports(rawSource, file) {
2296
+ const source = stripComments(rawSource);
2297
+ const imports = {
2298
+ hosts: [],
2299
+ outputs: []
2300
+ };
2301
+ for (const match of source.matchAll(/^\s*import\b[^;'"]*?from\s+["']([^"']+)["']/gm)) {
2302
+ const specifier = match[1];
2303
+ if (specifier.endsWith(CONFIG_IMPORT_SUFFIX)) continue;
2304
+ const sibling = SIBLING_IMPORT.exec(specifier);
2305
+ if (sibling) {
2306
+ (sibling[2] === HOST_FILE ? imports.hosts : imports.outputs).push(sibling[1]);
2307
+ continue;
2308
+ }
2309
+ throw new HostLoadError(`${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.`, "Host files are static projections; code belongs in plugins or the runner.");
2310
+ }
2311
+ if (/^\s*import\s+["']/m.test(source)) throw new HostLoadError(`${file} contains a side-effect import — a host file may only import the project's powerhouse.config.json or sibling host files.`);
2312
+ if (/\bimport\s*\(/.test(source) || /\brequire\s*\(/.test(source)) throw new HostLoadError(`${file} uses dynamic import()/require() — host files are static data.`);
2313
+ rejectProcessAccess(source, file);
2314
+ return imports;
2315
+ }
2316
+ /** A generated `outputs.js` is plain data: no imports of any kind, no
2317
+ * dynamic import/require, no `process.`. */
2318
+ function lintOutputsFile(rawSource, file) {
2319
+ const source = stripComments(rawSource);
2320
+ if (/^\s*import\b/m.test(source) || /^\s*export\b[^;]*?\bfrom\s+["']/m.test(source) || /\bimport\s*\(/.test(source) || /\brequire\s*\(/.test(source)) throw new HostLoadError(`${file} imports a module — a generated ${OUTPUTS_FILE} is plain data.`, "Regenerate it with `ph generate hosts` instead of editing it.");
2321
+ rejectProcessAccess(source, file);
2322
+ }
2323
+ /** Walks the sibling-import graph from `hostName`, linting every visited file
2324
+ * (and every outputs.js it imports) and failing on a cycle (an ESM circular
2325
+ * would otherwise surface as an undefined default export with no useful
2326
+ * message). Returns the hosts whose outputs.js the graph imports, sorted. */
2327
+ function lintHostImportGraph(hostsDir, hostName) {
2328
+ const state = /* @__PURE__ */ new Map();
2329
+ const producers = /* @__PURE__ */ new Set();
2330
+ const visit = (name, chain) => {
2331
+ const mark = state.get(name);
2332
+ if (mark === "done") return;
2333
+ if (mark === "visiting") throw new HostLoadError(`Host import cycle: ${[...chain, name].map((n) => `hosts/${n}`).join(" -> ")}.`, "Hoist the shared data into one host (or powerhouse.config.json) instead of importing both ways.");
2334
+ const file = path.join(hostsDir, name, HOST_FILE);
2335
+ if (!existsSync(file)) throw new HostLoadError(`hosts/${chain[chain.length - 1] ?? name} imports sibling "hosts/${name}/host.js", which does not exist.`);
2336
+ state.set(name, "visiting");
2337
+ const imports = scanHostImports(readFileSync(file, "utf8"), file);
2338
+ for (const producer of imports.outputs) {
2339
+ if (producers.has(producer)) continue;
2340
+ const outputsFile = path.join(hostsDir, producer, OUTPUTS_FILE);
2341
+ if (!existsSync(outputsFile)) throw new HostLoadError(`hosts/${name}/host.js imports "hosts/${producer}/${OUTPUTS_FILE}", which does not exist.`, GENERATE_HINT);
2342
+ lintOutputsFile(readFileSync(outputsFile, "utf8"), outputsFile);
2343
+ producers.add(producer);
2344
+ }
2345
+ for (const sibling of imports.hosts) visit(sibling, [...chain, name]);
2346
+ state.set(name, "done");
2347
+ };
2348
+ visit(hostName, []);
2349
+ return [...producers].sort();
2350
+ }
2351
+ /** Returns the path of the first value that would not survive a JSON round
2352
+ * trip, or undefined when the object is fully static. */
2353
+ function findNonStaticValue(value, trail = "") {
2354
+ if (value === null) return void 0;
2355
+ const kind = typeof value;
2356
+ if (kind === "string" || kind === "number" || kind === "boolean") return;
2357
+ if (kind !== "object") return `${trail || "<root>"} (${kind})`;
2358
+ if (Array.isArray(value)) {
2359
+ for (let i = 0; i < value.length; i++) {
2360
+ const hit = findNonStaticValue(value[i], `${trail}[${i}]`);
2361
+ if (hit) return hit;
2362
+ }
2363
+ return;
2364
+ }
2365
+ const proto = Object.getPrototypeOf(value);
2366
+ if (proto !== Object.prototype && proto !== null) return `${trail || "<root>"} (non-plain object)`;
2367
+ for (const [key, child] of Object.entries(value)) {
2368
+ const hit = findNonStaticValue(child, trail ? `${trail}.${key}` : key);
2369
+ if (hit) return hit;
2370
+ }
2371
+ }
2372
+ function assertHostShape(host, file) {
2373
+ if (typeof host.name !== "string" || host.name.length === 0) throw new HostLoadError(`${file}: \`name\` must be a non-empty string.`);
2374
+ const runner = host.runner;
2375
+ if (runner === null || typeof runner !== "object" || typeof runner.module !== "string") throw new HostLoadError(`${file}: \`runner\` must be an object with a \`module\` specifier string.`);
2376
+ if (host.reactor !== void 0 && host.children !== void 0) throw new HostLoadError(`${file}: \`reactor\` and \`children\` are mutually exclusive — a host is a reactor runner or a compound runner, never both.`);
2377
+ }
2378
+ async function loadHost(projectRoot, hostName) {
2379
+ return importHost(projectRoot, hostName, true);
2380
+ }
2381
+ async function importHost(projectRoot, hostName, checkOutputs) {
2382
+ const probe = probeHostsFolder(projectRoot);
2383
+ if (probe.kind === "absent") throw new HostLoadError(`No hosts/ folder found in ${projectRoot}.`, "Scaffold one with `ph init --uniform-runners` (or create hosts/<name>/host.js).");
2384
+ if (probe.kind === "empty") throw new HostLoadError(`hosts/ exists at ${probe.dir} but contains no <name>/host.js.`, "An empty hosts/ folder does not activate the uniform-runners architecture; add a host definition or remove the folder.");
2385
+ if (!probe.hosts.includes(hostName)) throw new HostLoadError(`Unknown host "${hostName}". Available hosts: ${probe.hosts.join(", ")}.`);
2386
+ const file = path.join(probe.dir, hostName, HOST_FILE);
2387
+ const producers = lintHostImportGraph(probe.dir, hostName);
2388
+ if (checkOutputs) for (const producer of producers) await assertOutputsFileFresh(projectRoot, probe.dir, hostName, producer);
2389
+ const host = (await import(pathToFileURL(file).href)).default;
2390
+ if (host === null || typeof host !== "object" || Array.isArray(host)) throw new HostLoadError(`${file} must default-export the host object (\`export default { name, runner, ... }\`).`);
2391
+ const nonStatic = findNonStaticValue(host);
2392
+ if (nonStatic) throw new HostLoadError(`${file} exports a non-static value at \`${nonStatic}\` — host files must survive a JSON round trip.`, "Runtime behavior belongs in the runner; host files only carry data.");
2393
+ assertHostShape(host, file);
2394
+ return {
2395
+ name: hostName,
2396
+ dir: path.dirname(file),
2397
+ file,
2398
+ host
2399
+ };
2400
+ }
2401
+ const OUTPUTS_HASH_EXPORT = /^export const outputsHash = "([^"]+)";$/m;
2402
+ /** The hash a generated outputs.js carries, or undefined. */
2403
+ function readOutputsFileHash(source) {
2404
+ return OUTPUTS_HASH_EXPORT.exec(source)?.[1];
2405
+ }
2406
+ function canonicalJson(value) {
2407
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
2408
+ if (value !== null && typeof value === "object") return `{${Object.entries(value).filter(([, child]) => child !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`).join(",")}}`;
2409
+ return JSON.stringify(value);
2410
+ }
2411
+ /** sha256 over the canonical JSON of the generator's inputs. The host name
2412
+ * is one: every token in the file carries it, so a copied or renamed host
2413
+ * folder makes its outputs.js stale. */
2414
+ function computeOutputsHash(input) {
2415
+ return `sha256:${createHash("sha256").update(canonicalJson({
2416
+ v: 1,
2417
+ host: input.host,
2418
+ runnerModule: input.runnerModule,
2419
+ outputsSchema: input.outputsSchema,
2420
+ drives: [...new Set(input.drives)].sort()
2421
+ })).digest("hex").slice(0, 32)}`;
2422
+ }
2423
+ function isZodSchema(value) {
2424
+ return value !== null && typeof value === "object" && "_zod" in value;
2425
+ }
2426
+ function isRecord$1(value) {
2427
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2428
+ }
2429
+ /** Local (non-remote) slugs from a drive declaration list. */
2430
+ function localDriveSlugs(drives) {
2431
+ if (!Array.isArray(drives)) return [];
2432
+ return drives.flatMap((drive) => isRecord$1(drive) && typeof drive.slug === "string" && drive.remote === void 0 ? [drive.slug] : []);
2433
+ }
2434
+ /**
2435
+ * Describes the outputs a host's creation produces, for `ph generate hosts`
2436
+ * and the loader's staleness check: the runner's `outputsSchema` as JSON
2437
+ * Schema and the host's declared local drives (the keys `drives.<slug>` of a
2438
+ * switchboard-like runner). Returns undefined when the runner exports no
2439
+ * `outputsSchema` (the host produces nothing a token can reference).
2440
+ *
2441
+ * Plugin-contributed drives are collected across every verb (verb scoping
2442
+ * is ignored: a drive any verb serves is referenceable). Plugins the project
2443
+ * tree cannot resolve contribute nothing, exactly as at boot. The implicit
2444
+ * default drive a switchboard serves when it declares none is NOT a known
2445
+ * key (it is not declared); reach it with a literal `$output` token.
2446
+ */
2447
+ async function describeHostOutputs(projectRoot, hostName) {
2448
+ const { host, file } = await importHost(projectRoot, hostName, false);
2449
+ const runnerModule = host.runner.module;
2450
+ const schema = (await resolveRunnerModule(projectRoot, runnerModule)).outputsSchema;
2451
+ if (!isZodSchema(schema)) return void 0;
2452
+ const { $schema: _dialect, ...outputsSchema } = toJSONSchema(schema, {
2453
+ io: "output",
2454
+ unrepresentable: "any"
2455
+ });
2456
+ const reactor = host.reactor;
2457
+ const drives = localDriveSlugs(isRecord$1(reactor) ? reactor.drives : []);
2458
+ const entries = (host.runner.plugins ?? []).map((entry) => typeof entry === "string" ? entry : {
2459
+ ...entry,
2460
+ verbs: "*"
2461
+ });
2462
+ if (entries.length > 0) {
2463
+ const plan = await resolvePluginContributions(projectRoot, "*", entries, path.relative(projectRoot, file));
2464
+ drives.push(...localDriveSlugs(plan.drives.map((drive) => drive.declaration)));
2465
+ }
2466
+ const sortedDrives = [...new Set(drives)].sort();
2467
+ return {
2468
+ host: hostName,
2469
+ runnerModule,
2470
+ outputsSchema,
2471
+ drives: sortedDrives,
2472
+ hash: computeOutputsHash({
2473
+ host: hostName,
2474
+ runnerModule,
2475
+ outputsSchema,
2476
+ drives: sortedDrives
2477
+ })
2478
+ };
2479
+ }
2480
+ async function assertOutputsFileFresh(projectRoot, hostsDir, consumer, producer) {
2481
+ const rel = `hosts/${producer}/${OUTPUTS_FILE}`;
2482
+ const actual = readOutputsFileHash(readFileSync(path.join(hostsDir, producer, OUTPUTS_FILE), "utf8"));
2483
+ if (!existsSync(path.join(hostsDir, producer, HOST_FILE))) throw new HostLoadError(`hosts/${consumer} imports ${rel}, but there is no hosts/${producer}/host.js to produce it.`, "Delete the orphaned outputs.js and fix the import.");
2484
+ const description = await describeHostOutputs(projectRoot, producer);
2485
+ if (!description) throw new HostLoadError(`hosts/${consumer} imports ${rel}, but hosts/${producer}'s runner declares no outputsSchema, so it produces no outputs.`);
2486
+ if (actual !== description.hash) throw new HostLoadError(`${rel} is stale (its producer's outputsSchema or declared drives changed since it was generated); run \`ph generate hosts\`.`, actual === void 0 ? `${rel} carries no outputsHash export; it was not generated by \`ph generate hosts\`.` : `expected ${description.hash}, found ${actual}.`);
2487
+ }
2488
+ /**
2489
+ * `.ph/run/<host>.json`, version 2 (typed-host-configs 3.6): what a running
2490
+ * host and its members produced. Validated on read; a v1 (or any invalid)
2491
+ * record reads as "not running". `projectName` is kept beyond the plan's
2492
+ * sketch because the live/foreign probe needs it. `host` is the host's
2493
+ * `name` (the file key), not its folder.
2494
+ */
2495
+ const outputsSchema = record(string(), unknown());
2496
+ const runRecordMemberSchema = strictObject({
2497
+ /** The member's host folder (`children.<key>.host`). */
2498
+ host: string().min(1),
2499
+ runnerModule: string().min(1),
2500
+ kind: runnerKindSchema,
2501
+ verb: string().min(1),
2502
+ outputs: outputsSchema
2503
+ });
2504
+ const runRecordSchema = strictObject({
2505
+ version: literal(2),
2506
+ host: hostNameSchema,
2507
+ projectName: string(),
2508
+ kind: runnerKindSchema,
2509
+ verb: string().min(1),
2510
+ pid: number().int(),
2511
+ startedAt: string(),
2512
+ /** Standalone hosts: the runner's outputs. */
2513
+ outputs: outputsSchema.optional(),
2514
+ /** Compounds: one entry per started member, keyed by member name. */
2515
+ members: record(string(), runRecordMemberSchema).optional(),
2516
+ /** Host-specific extras (e.g. mcpUrl) a runner wants in the record. */
2517
+ extra: record(string(), unknown()).optional()
2518
+ });
2519
+ const runDir = (projectDir, env = process.env) => path.join(resolvePhDir(projectDir, env), "run");
2520
+ function recordPath(projectDir, hostName, env) {
2521
+ const dir = runDir(projectDir, env);
2522
+ const file = path.resolve(dir, `${hostName}.json`);
2523
+ if (!hostNameSchema.safeParse(hostName).success || path.dirname(file) !== path.resolve(dir)) throw new Error(`"${hostName}" can't name a run record. ${HOST_NAME_MESSAGE}`);
2524
+ return file;
2525
+ }
2526
+ function readRunRecord(projectDir, hostName, env = process.env) {
2527
+ let raw;
2528
+ try {
2529
+ raw = JSON.parse(fs.readFileSync(recordPath(projectDir, hostName, env), "utf8"));
2530
+ } catch {
2531
+ return;
2532
+ }
2533
+ const parsed = runRecordSchema.safeParse(raw);
2534
+ return parsed.success ? parsed.data : void 0;
2535
+ }
2536
+ /** Every valid v2 record under `.ph/run/` (invalid and v1 files skipped). */
2537
+ function listRunRecords(projectDir, env = process.env) {
2538
+ let files;
2539
+ try {
2540
+ files = fs.readdirSync(runDir(projectDir, env));
2541
+ } catch {
2542
+ return [];
2543
+ }
2544
+ return files.filter((file) => file.endsWith(".json")).flatMap((file) => {
2545
+ const record = readRunRecord(projectDir, file.slice(0, -5), env);
2546
+ return record ? [record] : [];
2547
+ });
2548
+ }
2549
+ /** The project identity the live/foreign probe compares: package.json
2550
+ * `name`, else the folder name. */
2551
+ function readProjectName(projectDir) {
2552
+ try {
2553
+ const pkg = JSON.parse(fs.readFileSync(path.join(projectDir, "package.json"), "utf8"));
2554
+ if (typeof pkg.name === "string" && pkg.name) return pkg.name;
2555
+ } catch {}
2556
+ return path.basename(path.resolve(projectDir));
2557
+ }
2558
+ function writeRunRecord(projectDir, record) {
2559
+ const target = recordPath(projectDir, record.host);
2560
+ const valid = runRecordSchema.parse(record);
2561
+ fs.mkdirSync(path.dirname(target), { recursive: true });
2562
+ fs.writeFileSync(target, `${JSON.stringify(valid, null, 2)}\n`);
2563
+ }
2564
+ function clearRunRecord(projectDir, hostName, env = process.env) {
2565
+ try {
2566
+ fs.rmSync(recordPath(projectDir, hostName, env));
2567
+ } catch {}
2568
+ }
2569
+ function isPidAlive(pid) {
2570
+ try {
2571
+ process.kill(pid, 0);
2572
+ return true;
2573
+ } catch (error) {
2574
+ return error.code === "EPERM";
2575
+ }
2576
+ }
2577
+ /**
2578
+ * Decide whether the recorded instance is this project's live host.
2579
+ *
2580
+ * pid liveness alone proves nothing (pids are reused), and the recorded
2581
+ * projectName is what separates "my instance" from "a different project that
2582
+ * happens to hold this storage root" — the confusion the vetra lock exists to
2583
+ * prevent. A stale record (dead pid) is reported so the caller can clear it; a
2584
+ * foreign one (live pid, different project) is left alone.
2585
+ */
2586
+ function probeRun(projectDir, hostName, projectName, env = process.env) {
2587
+ const record = readRunRecord(projectDir, hostName, env);
2588
+ if (!record) return { status: "none" };
2589
+ if (!isPidAlive(record.pid)) return {
2590
+ status: "stale",
2591
+ record
2592
+ };
2593
+ if (record.projectName !== projectName) return {
2594
+ status: "foreign",
2595
+ record
2596
+ };
2597
+ return {
2598
+ status: "live",
2599
+ record
2600
+ };
2601
+ }
2602
+ /** Generic compound rule: `reactor`/`config` replace, `runner` key-merges. */
2603
+ function applyChildWrapper(base, wrapper) {
2604
+ const reactor = wrapper.reactor ?? base.reactor;
2605
+ const config = wrapper.config ?? base.config;
2606
+ return {
2607
+ ...base,
2608
+ runner: {
2609
+ ...base.runner,
2610
+ ...wrapper.runner
2611
+ },
2612
+ ...config !== void 0 ? { config } : {},
2613
+ ...reactor !== void 0 ? { reactor } : {}
2614
+ };
2615
+ }
2616
+ /**
2617
+ * `${userData}` resolution for host files (desktop shape): storage paths in a
2618
+ * host must not derive from the instance name (renames must stay safe), so
2619
+ * the host file writes `${userData}/.ph/reactor-storage` and the RUNNER
2620
+ * resolves it at start. `${userData}` is a PROJECT-SHAPED root: its `.ph`
2621
+ * subtree carries the same names the classic commands use under
2622
+ * `<project>/.ph` (see `resolvePhDir`). In the CLI it IS the project root, so
2623
+ * `ph run desktop` in a project shares the one `.ph` tree `ph vetra` uses;
2624
+ * a shell (Tauri) points it at the OS profile via PH_USER_DATA_DIR, and the
2625
+ * whole `.ph` tree — stores, identity, run records — follows.
2626
+ */
2627
+ function defaultUserDataDir(projectRoot, env = process.env) {
2628
+ return env.PH_USER_DATA_DIR ?? path.resolve(projectRoot);
2629
+ }
2630
+ /** Load every producer host a set of refs names (each once). */
2631
+ async function loadProducers(projectRoot, refs) {
2632
+ const producers = /* @__PURE__ */ new Map();
2633
+ for (const { host: folder } of refs) {
2634
+ if (producers.has(folder)) continue;
2635
+ try {
2636
+ const loaded = await loadHost(projectRoot, folder);
2637
+ const specifier = loaded.host.runner.module;
2638
+ producers.set(folder, {
2639
+ folder,
2640
+ name: loaded.host.name,
2641
+ specifier,
2642
+ runner: await resolveRunnerModule(projectRoot, specifier)
2643
+ });
2644
+ } catch (error) {
2645
+ producers.set(folder, { error: `names host "${folder}", which cannot be loaded: ${error instanceof Error ? error.message : String(error)}` });
2646
+ }
2647
+ }
2648
+ return producers;
2649
+ }
2650
+ /** The outputs schema of a runner module, or why it has none. */
2651
+ function runnerOutputsSchema(runner, specifier, label) {
2652
+ const schema = runner.outputsSchema;
2653
+ if (schema === void 0 || schema === null) return { error: `${label} runs "${specifier}", which exports no outputsSchema, so it produces no outputs a token can read.` };
2654
+ return {
2655
+ schema,
2656
+ label: `"${specifier}" (${label})`
2657
+ };
2658
+ }
2659
+ /** Declared-validation lookup for a standalone host's producers. */
2660
+ function producerOutputsSchemas(producers) {
2661
+ return (ref) => {
2662
+ const info = producers.get(ref.host);
2663
+ if (!info) return { error: `names host "${ref.host}", which was not loaded.` };
2664
+ if ("error" in info) return { error: info.error };
2665
+ return runnerOutputsSchema(info.runner, info.specifier, `host "${ref.host}"`);
2666
+ };
2667
+ }
2668
+ /**
2669
+ * Standalone `$output` source: the producer's live v2 run record. Its own
2670
+ * standalone record first (keyed by the producer's `name`); else a live
2671
+ * compound of this project with exactly one member running that host. A
2672
+ * missing, stale, foreign or output-less record means "not running", and the
2673
+ * lookup fails naming the producer and how to start it (no fallback to the
2674
+ * producer's declared config, no waiting).
2675
+ */
2676
+ function runRecordOutputSource(projectRoot, options) {
2677
+ const { consumer, producers, projectName } = options;
2678
+ return { lookup(ref) {
2679
+ const notRunning = `${consumer} needs outputs from host "${ref.host}", which is not running. Start it first: ph run ${ref.host} (or run a compound that includes it).`;
2680
+ const info = producers.get(ref.host);
2681
+ const schema = info && !("error" in info) ? info.runner.outputsSchema : void 0;
2682
+ const withSchema = schema !== void 0 && schema !== null ? { schema } : {};
2683
+ if (ref.member === void 0 && info && !("error" in info)) {
2684
+ const probe = probeRun(projectRoot, info.name, projectName);
2685
+ if (probe.status === "live" && probe.record.outputs) return {
2686
+ status: "available",
2687
+ outputs: probe.record.outputs,
2688
+ ...withSchema
2689
+ };
2690
+ }
2691
+ const members = listRunRecords(projectRoot).filter((record) => record.members !== void 0 && record.projectName === projectName && isPidAlive(record.pid)).flatMap((record) => Object.entries(record.members ?? {}).filter(([key, member]) => member.host === ref.host && (ref.member === void 0 || key === ref.member)).map(([key, member]) => ({
2692
+ compound: record.host,
2693
+ key,
2694
+ member
2695
+ })));
2696
+ if (members.length === 1) return {
2697
+ status: "available",
2698
+ outputs: members[0].member.outputs,
2699
+ ...withSchema
2700
+ };
2701
+ if (members.length > 1) return {
2702
+ status: "unavailable",
2703
+ message: `${consumer} needs outputs from host "${ref.host}", which runs as ${members.map((m) => `member "${m.key}" of "${m.compound}"`).join(" and ")}; stop all but one, or run ${ref.host} on its own.`
2704
+ };
2705
+ return {
2706
+ status: "unavailable",
2707
+ message: notRunning
2708
+ };
2709
+ } };
2710
+ }
2711
+ /** The resolving process's `$env` inputs: its environment plus the
2712
+ * always-resolvable built-ins (`userData` honours PH_USER_DATA_DIR). */
2713
+ function processResolveEnv(projectRoot, env = process.env) {
2714
+ return {
2715
+ env,
2716
+ builtins: {
2717
+ userData: defaultUserDataDir(projectRoot, env),
2718
+ projectRoot: path.resolve(projectRoot)
2719
+ }
2720
+ };
2721
+ }
2722
+ /**
2723
+ * The compound output source: a member's `$output` tokens read the live
2724
+ * `RunnerHandle.outputs` of the members started before it. `schemas` (member
2725
+ * key → its runner's `outputsSchema`) lets an absent optional output field
2726
+ * omit the consuming property. Pure (the run-record source for standalone
2727
+ * hosts is node: ./node.ts).
2728
+ */
2729
+ function compoundOutputSource(members, started, compound, schemas) {
2730
+ return { lookup(ref) {
2731
+ const target = memberForRef(ref, members);
2732
+ if ("error" in target) return {
2733
+ status: "unavailable",
2734
+ message: `compound "${compound}": a token ${target.error}`
2735
+ };
2736
+ if (!started.has(target.key)) return {
2737
+ status: "unavailable",
2738
+ message: `compound "${compound}": member "${target.key}" (host "${ref.host}") has not started yet; a producer must start before its consumers.`
2739
+ };
2740
+ const schema = schemas?.get(target.key);
2741
+ return {
2742
+ status: "available",
2743
+ outputs: started.get(target.key),
2744
+ ...schema !== void 0 ? { schema } : {}
2745
+ };
2746
+ } };
2747
+ }
2748
+ /** The data half of a handle, validated by the compound. `ready`/`shutdown`
2749
+ * are functions and promises, so they are checked as TS fields, not here. */
2750
+ const runnerHandleSchema = looseObject({ outputs: record(string(), unknown()).optional() });
2751
+ function isRecord(value) {
2752
+ return typeof value === "object" && value !== null;
2753
+ }
2754
+ function isPromiseLike(value) {
2755
+ return isRecord(value) && typeof value.then === "function";
2756
+ }
2757
+ function isCallable(value) {
2758
+ return typeof value === "function";
2759
+ }
2760
+ /** Normalize what a verb returned. `undefined` (a self-sustaining bridge)
2761
+ * is an empty handle; anything else must match runnerHandleSchema. */
2762
+ function toStartedHandle(value, where) {
2763
+ if (value === void 0 || value === null) return { outputs: {} };
2764
+ const parsed = runnerHandleSchema.safeParse(value);
2765
+ if (!parsed.success) throw new Error(`${where} returned an invalid runner handle:\n${prettifyError(parsed.error)}`);
2766
+ const live = isRecord(value) ? value : {};
2767
+ const shutdown = live.shutdown;
2768
+ return {
2769
+ ...parsed.data,
2770
+ outputs: parsed.data.outputs ?? {},
2771
+ ...isPromiseLike(live.ready) ? { ready: live.ready } : {},
2772
+ ...isCallable(shutdown) ? { shutdown: () => shutdown.call(value) } : {}
2773
+ };
2774
+ }
2775
+ async function memberDraft(projectRoot, member) {
2776
+ return applyChildWrapper((await loadHost(projectRoot, member.host)).host, member);
2777
+ }
2778
+ /** Whether a member receives the compound's `cspRegistrySync` wiring (as
2779
+ * `runner.cspRegistrySync`): its runner declares that option (any specifier
2780
+ * that reaches the Connect runner), or it names the Connect runner. A
2781
+ * member's role is its runner, not its folder. */
2782
+ function takesCspRegistrySync(m) {
2783
+ return m.specifier === "@powerhousedao/ph-cli/runners/connect" || declaresKey(m.runner.hostSchema, ["runner"], "cspRegistrySync");
2784
+ }
2785
+ /** The verb the generic compound starts its members at for its own `verb`:
2786
+ * `run` follows the compound's defaultVerb. */
2787
+ function compoundStartVerb(verb, runner) {
2788
+ return verb === "run" ? runner.defaultVerb ?? "run" : verb;
2789
+ }
2790
+ /** At compound verb "run" each member runs its own (merged) defaultVerb —
2791
+ * what lets a desktop compound pair a switchboard at `run` with a connect at
2792
+ * `serve`. An explicit forwarded verb stays uniform across members. */
2793
+ function memberVerbOf(compoundVerb, runner) {
2794
+ return compoundVerb === "run" ? runner.defaultVerb ?? "run" : compoundVerb;
2795
+ }
2796
+ /** One member's draft and runner. */
2797
+ async function prepareMember(projectRoot, key, member) {
2798
+ const draft = await memberDraft(projectRoot, member);
2799
+ const specifier = draft.runner.module;
2800
+ return {
2801
+ key,
2802
+ member,
2803
+ draft,
2804
+ specifier,
2805
+ runner: await resolveRunnerModule(projectRoot, specifier),
2806
+ file: `hosts/${member.host}/host.js`
2807
+ };
2808
+ }
2809
+ //#endregion
2810
+ export { takesCspRegistrySync as $, loadProducers as A, processResolveEnv as B, hostSchemaIssues as C, isToken as D, isSchemaLike as E, outputSitesOf as F, renderTokens as G, projectDriveIdWith as H, planCompound as I, resolvePluginContributions as J, resolveHostOutputs as K, prepareMember as L, memberVerbOf as M, normalizePluginEntries as N, kindShapeIssues as O, outputRefsOf as P, substituteBuiltinEnv as Q, probeHostsFolder as R, getVerb as S, isPlainObject as T, readProjectName as U, producerOutputsSchemas as V, readRunRecord as W, runRecordOutputSource as X, resolveRunnerModule as Y, runnerOutputsSchema as Z, entryActiveForVerb as _, TokenResolutionError as a, findRemovedForms as b, checkTokenSites as c, compoundOutputSource as d, toStartedHandle as et, compoundStartVerb as f, drivesSchema as g, describeToken as h, PluginError as i, writeRunRecord as it, memberForRef as j, loadHost as k, clearRunRecord as l, defineHostSchemas as m, HostLoadError as n, validateDeclaredHost as nt, applyChildWrapper as o, declaredHostSchemas as p, resolveHostPlugins as q, ONE_SHOT_VERBS as r, validateHost as rt, checkOutputPaths as s, CONNECT_RUNNER as t, unsetEnvMessage as tt, collectTokenSites as u, envSitesOf as v, isBuiltinEnvName as w, formatPath as x, findDeadConnectConfig as y, probeRun as z };
2811
+
2812
+ //# sourceMappingURL=compound-C7GuPnTP-Ba4ce2Xa.mjs.map
2813
+ //# debugId=57a0cfdd-936e-5667-92af-0b7932191a13