@powerhousedao/host-core 6.4.0-next.3 → 6.4.0-next.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/{compound-L62ALvYc.d.mts → compound-BLhEewO6.d.mts} +8 -2
  2. package/dist/compound-BLhEewO6.d.mts.map +1 -0
  3. package/dist/{compound-Q9sZSEZF.mjs → compound-g6x_KkWp.mjs} +133 -1208
  4. package/dist/compound-g6x_KkWp.mjs.map +1 -0
  5. package/dist/control-channel-DVn4dvfQ.d.mts +206 -0
  6. package/dist/control-channel-DVn4dvfQ.d.mts.map +1 -0
  7. package/dist/control-channel.d.mts +2 -2
  8. package/dist/control-channel.mjs +358 -47
  9. package/dist/control-channel.mjs.map +1 -1
  10. package/dist/host-entry-B8n_590_.mjs +188 -0
  11. package/dist/host-entry-B8n_590_.mjs.map +1 -0
  12. package/dist/index.d.mts +68 -102
  13. package/dist/index.d.mts.map +1 -1
  14. package/dist/index.mjs +6 -3
  15. package/dist/index.mjs.map +1 -1
  16. package/dist/instance-C6uugZ32.d.mts +165 -0
  17. package/dist/instance-C6uugZ32.d.mts.map +1 -0
  18. package/dist/instance.d.mts +3 -0
  19. package/dist/instance.mjs +145 -0
  20. package/dist/instance.mjs.map +1 -0
  21. package/dist/kill-tree.d.mts +2 -0
  22. package/dist/kill-tree.d.mts.map +1 -1
  23. package/dist/kill-tree.mjs +1 -1
  24. package/dist/kill-tree.mjs.map +1 -1
  25. package/dist/run-record-C6oTZF_C.mjs +1077 -0
  26. package/dist/run-record-C6oTZF_C.mjs.map +1 -0
  27. package/dist/runners/compound.d.mts +1 -1
  28. package/dist/runners/compound.mjs +2 -1
  29. package/dist/runners/compound.mjs.map +1 -1
  30. package/dist/spawn-host-DWroRe1S.d.mts +107 -0
  31. package/dist/spawn-host-DWroRe1S.d.mts.map +1 -0
  32. package/dist/supervisor-record.d.mts +88 -0
  33. package/dist/supervisor-record.d.mts.map +1 -0
  34. package/dist/supervisor-record.mjs +127 -0
  35. package/dist/supervisor-record.mjs.map +1 -0
  36. package/dist/supervisor.d.mts +205 -0
  37. package/dist/supervisor.d.mts.map +1 -0
  38. package/dist/supervisor.mjs +905 -0
  39. package/dist/supervisor.mjs.map +1 -0
  40. package/package.json +21 -3
  41. package/dist/compound-L62ALvYc.d.mts.map +0 -1
  42. package/dist/compound-Q9sZSEZF.mjs.map +0 -1
  43. package/dist/control-channel-eqvyUF03.d.mts +0 -123
  44. package/dist/control-channel-eqvyUF03.d.mts.map +0 -1
@@ -0,0 +1,1077 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { z } from "zod";
4
+ import { TOKEN_ESCAPE_KEY, TOKEN_KEYS, concatTokenSchema, envTokenSchema, envTokenable, findToken, forbidRef, isToken, itemTokenSchema, keyTokenSchema, mapTokenSchema, outputTokenSchema, ref, switchboardOfDrive, tokenKeyOf, tokenSchema, tokenable } from "@powerhousedao/shared/host-tokens";
5
+ import { isOriginPlaceholderUrl } from "@powerhousedao/shared/connect/origin-placeholder";
6
+ import { execFileSync } from "node:child_process";
7
+ import { createOwnerOnlyFile, fileAccessList, restrictFileToOwner, writeOwnerOnlyFile } from "@powerhousedao/shared/clis/owner-only";
8
+ //#region src/drive-schema.ts
9
+ /**
10
+ * The schema half of drives.ts, zod only so `./schema` stays neutral.
11
+ * - slug: the SEEDING KEY (idempotence); id optional (stable identity).
12
+ * - preferredEditor: stored at header.meta.preferredEditor; Connect config's
13
+ * `app` is the legacy alias.
14
+ * - remote.url: a drive served elsewhere; local fields are ignored for it.
15
+ * Token-able (`$output` on a producer's `drives.<slug>.url`).
16
+ */
17
+ function buildDriveDeclarationSchema(urlField) {
18
+ return z.strictObject({
19
+ slug: z.string().min(1),
20
+ id: z.string().min(1).optional(),
21
+ /** Derive the id from the project path (`<slug>-<hash of the path>`) — the
22
+ * same ids classic `ph vetra` produced. `true` serves the drive under the
23
+ * hashed slug too (the vetra drive's slug IS its hashed id); `"id"` hashes
24
+ * only the id and keeps the declared slug (the classic Workflows drive:
25
+ * `/d/workflows`, id `workflows-<hash>`). */
26
+ projectHash: z.union([z.boolean(), z.literal("id")]).optional(),
27
+ /** What a missing drive is created as. Default powerhouse/document-drive. */
28
+ documentType: z.enum(["powerhouse/document-drive", "powerhouse/reactor-drive"]).optional(),
29
+ name: z.string().min(1).optional(),
30
+ icon: z.string().optional(),
31
+ preferredEditor: z.string().optional(),
32
+ sharingType: z.enum([
33
+ "public",
34
+ "private",
35
+ "shared"
36
+ ]).optional(),
37
+ availableOffline: z.boolean().optional(),
38
+ remote: z.strictObject({ url: urlField(z.string().min(1)) }).optional()
39
+ });
40
+ }
41
+ const driveDeclarationSchema = buildDriveDeclarationSchema(tokenable);
42
+ const drivesSchema = z.array(driveDeclarationSchema);
43
+ /** The project-hashed drive id (`${slug}-${sha256(projectRoot)[0..8]}`) with
44
+ * the hash function injected, so neutral consumers (a browser monitor) can
45
+ * pass `crypto.subtle`-derived or precomputed hex. drives.ts binds it to
46
+ * node:crypto as `projectDriveId`. */
47
+ function projectDriveIdWith(sha256Hex, projectRoot, slug) {
48
+ return `${slug}-${sha256Hex(projectRoot).substring(0, 8)}`;
49
+ }
50
+ //#endregion
51
+ //#region src/plugins.ts
52
+ /**
53
+ * R1 — the host plugin framework (bridge-runners-to-plugins plan,
54
+ * customization-references/host-core as the blueprint).
55
+ *
56
+ * A plugin is hooks + contributions; hooks are boot wiring (main realm only),
57
+ * contributions are declarative, serializable surface. Host RUNTIMES define
58
+ * the hook vocabulary and interleave their own wiring between stages — they
59
+ * are never plugins themselves.
60
+ *
61
+ * host.js carries the COMPOSITION as `runner.plugins` entries:
62
+ * string | { module, enabled?, verbs?, config? }
63
+ * Presence is activation (enabled defaults true); `verbs` scopes an entry to
64
+ * matching run verbs; `config` is validated against the plugin's declared
65
+ * zod schema. Entries resolve from the PROJECT's dependency tree exactly
66
+ * like runner modules.
67
+ */
68
+ var PluginError = class extends Error {
69
+ constructor(message, hint) {
70
+ super(hint ? `${message}\n Hint: ${hint}` : message);
71
+ this.name = "PluginError";
72
+ }
73
+ };
74
+ const pluginEntryObjectSchema = z.strictObject({
75
+ module: z.string().min(1),
76
+ /** Presence is activation BY DEFAULT; false is the explicit off-switch. */
77
+ enabled: z.boolean().optional(),
78
+ /** "*" (default) or the run verbs this entry is active for. */
79
+ verbs: z.union([z.literal("*"), z.array(z.string().min(1)).min(1)]).optional(),
80
+ /** Validated against the plugin's declared configSchema at resolution. */
81
+ config: z.record(z.string(), z.unknown()).optional()
82
+ });
83
+ const pluginEntrySchema = z.union([z.string().min(1), pluginEntryObjectSchema]);
84
+ function normalizePluginEntry(entry) {
85
+ if (typeof entry === "string") return {
86
+ module: entry,
87
+ enabled: true,
88
+ verbs: "*",
89
+ config: {}
90
+ };
91
+ return {
92
+ module: entry.module,
93
+ enabled: entry.enabled ?? true,
94
+ verbs: entry.verbs ?? "*",
95
+ config: entry.config ?? {}
96
+ };
97
+ }
98
+ /** Module is the identity key: a duplicate makes override targeting and
99
+ * ordering ambiguous, so it fails loudly. */
100
+ function normalizePluginEntries(entries, where) {
101
+ const normalized = entries.map(normalizePluginEntry);
102
+ const seen = /* @__PURE__ */ new Set();
103
+ for (const entry of normalized) {
104
+ 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.");
105
+ seen.add(entry.module);
106
+ }
107
+ return normalized;
108
+ }
109
+ function entryActiveForVerb(entry, verb) {
110
+ if (!entry.enabled) return false;
111
+ return entry.verbs === "*" || entry.verbs.includes(verb);
112
+ }
113
+ /**
114
+ * The appliesTo hierarchy. "reactor" is the base every reactor host extends;
115
+ * "compound" is its own branch (plugins over the member set — e.g. the clint
116
+ * proxy). Host runtimes register their id with a parent; compatibility walks
117
+ * the parent chain.
118
+ */
119
+ const HOST_TYPE_PARENTS = {
120
+ reactor: null,
121
+ compound: null,
122
+ connect: "reactor",
123
+ switchboard: "reactor",
124
+ mastra: "reactor"
125
+ };
126
+ function registerHostType(id, parent) {
127
+ if (id in HOST_TYPE_PARENTS && HOST_TYPE_PARENTS[id] !== parent) throw new PluginError(`Host type "${id}" is already registered with parent "${String(HOST_TYPE_PARENTS[id])}".`);
128
+ HOST_TYPE_PARENTS[id] = parent;
129
+ }
130
+ function hostTypeSatisfies(hostType, appliesTo) {
131
+ let current = hostType;
132
+ while (current !== null) {
133
+ if (current === appliesTo) return true;
134
+ current = current in HOST_TYPE_PARENTS ? HOST_TYPE_PARENTS[current] : null;
135
+ }
136
+ return false;
137
+ }
138
+ /** Registration order, bucketed pre → normal → post (stable within buckets),
139
+ * then dependsOn topo-sorted within the bucketed order. */
140
+ function resolveOrder(plugins) {
141
+ const buckets = {
142
+ pre: [],
143
+ normal: [],
144
+ post: []
145
+ };
146
+ for (const plugin of plugins) buckets[plugin.enforce ?? "normal"].push(plugin);
147
+ const bucketed = [
148
+ ...buckets.pre,
149
+ ...buckets.normal,
150
+ ...buckets.post
151
+ ];
152
+ const byName = new Map(bucketed.map((p) => [p.name, p]));
153
+ for (const plugin of bucketed) for (const dep of plugin.dependsOn ?? []) if (!byName.has(dep)) throw new PluginError(`Plugin "${plugin.name}" depends on missing plugin "${dep}".`, "dependsOn names PLUGINS only — the host runtime is implied and never named.");
154
+ const ordered = [];
155
+ const state = /* @__PURE__ */ new Map();
156
+ const visit = (plugin, chain) => {
157
+ const mark = state.get(plugin.name);
158
+ if (mark === "done") return;
159
+ if (mark === "visiting") throw new PluginError(`Plugin dependency cycle: ${[...chain, plugin.name].join(" -> ")}.`);
160
+ state.set(plugin.name, "visiting");
161
+ for (const dep of plugin.dependsOn ?? []) visit(byName.get(dep), [...chain, plugin.name]);
162
+ state.set(plugin.name, "done");
163
+ ordered.push(plugin);
164
+ };
165
+ for (const plugin of bucketed) visit(plugin, []);
166
+ return ordered;
167
+ }
168
+ async function runProvideHook(name, plugins, ctx) {
169
+ const impls = plugins.filter((p) => typeof p.hooks?.[name] === "function");
170
+ if (impls.length > 1) throw new PluginError(`Hook "${name}" is provided by ${impls.map((p) => `"${p.name}"`).join(" and ")} — provide hooks have one winner.`);
171
+ const impl = impls[0]?.hooks?.[name];
172
+ return impl ? await impl(ctx) : void 0;
173
+ }
174
+ async function runTransformHook(name, plugins, ctx, seed) {
175
+ let value = seed;
176
+ for (const plugin of plugins) {
177
+ const impl = plugin.hooks?.[name];
178
+ if (typeof impl === "function") value = await impl(value, ctx);
179
+ }
180
+ return value;
181
+ }
182
+ /** Sequential observe, in plugin order — for lifecycle moments whose order
183
+ * is load-bearing (teardown: the switchboard stops privacy before workflows
184
+ * before the api, per the carve map). */
185
+ async function runObserveHookSequential(name, plugins, ctx) {
186
+ for (const plugin of plugins) {
187
+ const impl = plugin.hooks?.[name];
188
+ if (typeof impl === "function") await impl(ctx);
189
+ }
190
+ }
191
+ async function runObserveHook(name, plugins, ctx) {
192
+ await Promise.all(plugins.map(async (plugin) => {
193
+ const impl = plugin.hooks?.[name];
194
+ if (typeof impl === "function") await impl(ctx);
195
+ }));
196
+ }
197
+ /** Array kinds concatenate in provenance-then-order sequence (built-in first,
198
+ * so later sources read as overrides where consumers want last-wins). */
199
+ function mergeContributions(resolved) {
200
+ const rank = {
201
+ "built-in": 0,
202
+ local: 1,
203
+ dependency: 2
204
+ };
205
+ const sorted = [...resolved].sort((a, b) => rank[a.provenance] - rank[b.provenance]);
206
+ const merged = {};
207
+ for (const { plugin, provenance } of sorted) for (const [kind, values] of Object.entries(plugin.contributions ?? {})) {
208
+ if (!values) continue;
209
+ const bucket = merged[kind] ??= [];
210
+ for (const value of values) bucket.push({
211
+ value,
212
+ source: {
213
+ pluginName: plugin.name,
214
+ provenance
215
+ }
216
+ });
217
+ }
218
+ return merged;
219
+ }
220
+ //#endregion
221
+ //#region src/host-schemas.ts
222
+ /**
223
+ * The zod single source for host.js blocks (typed-host-configs G1). Every
224
+ * host type is z.input/z.output of these schemas; nothing is hand-mirrored.
225
+ * Top-level host objects and the `reactor` block are STRICT (a typo fails);
226
+ * `runner` stays loose until each runner declares its options (T2), and
227
+ * `config` is runner-defined.
228
+ *
229
+ * Token-able fields (typed-host-configs 3.5): `reactor.backends.*.remote.url`
230
+ * (required, a switchboard drive address), `reactor.drives` (whole list, e.g. `$map`),
231
+ * `reactor.drives[].remote.url` and `storage.dataDir` (`$env` only). Their z.input admits tokens, their z.output is the resolved type.
232
+ */
233
+ /** A host's `name` keys its run record, `.ph/run/<name>.json`, so it must be
234
+ * one safe path segment. */
235
+ const HOST_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
236
+ const HOST_NAME_MAX_LENGTH = 128;
237
+ 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.";
238
+ const hostNameSchema = z.string().min(1).max(128, HOST_NAME_MESSAGE).regex(HOST_NAME_PATTERN, HOST_NAME_MESSAGE);
239
+ /** An npm package name, as `<package>/<host>` names a package that supplies
240
+ * hosts: `name` or `@scope/name`, each part letters, digits, '-', '.', '_'
241
+ * and '~', not starting with '.' or '_'. Each part is one folder name, the
242
+ * one the package has under node_modules. */
243
+ const PACKAGE_NAME_PATTERN = /^(?:@[A-Za-z0-9~-][A-Za-z0-9._~-]*\/)?[A-Za-z0-9~-][A-Za-z0-9._~-]*$/;
244
+ /** How a compound names a member's host: its folder under the project's
245
+ * `hosts/` (or, in a package's compound, the package's first), or
246
+ * `<package>/<host>` for one an installed package supplies. */
247
+ const HOST_REF_PATTERN = new RegExp(`^(?:${PACKAGE_NAME_PATTERN.source.slice(1, -1)}/)?${HOST_NAME_PATTERN.source.slice(1, -1)}$`);
248
+ const HOST_REF_MESSAGE = "A member's host is a host folder (`switchboard`), or `<package>/<host>` (`@acme/tools/studio`) for one an installed package supplies.";
249
+ /**
250
+ * A URL, or one written against the page origin (`${origin}/graphql`): the
251
+ * browser resolves the placeholder when it loads Connect's config, for a
252
+ * member whose own server proxies the switchboard's paths.
253
+ */
254
+ const originOrUrlSchema = z.union([z.url(), z.string().refine(isOriginPlaceholderUrl, { message: "a URL, or ${origin}/<path> for a proxied sibling" })]);
255
+ const profileSchema = z.strictObject({
256
+ appId: z.string().min(1).optional(),
257
+ name: z.string().min(1).optional(),
258
+ description: z.string().optional(),
259
+ icon: z.string().optional()
260
+ });
261
+ const reactorProtocolSchema = z.strictObject({
262
+ featureFlags: z.strictObject({
263
+ documentDecisions: z.boolean().optional(),
264
+ authEnforcement: z.boolean().optional(),
265
+ authGroups: z.boolean().optional(),
266
+ authConditions: z.boolean().optional(),
267
+ undoV3: z.boolean().optional()
268
+ }).optional(),
269
+ createSignaturePolicy: z.enum(["legacy", "v2-required"]).optional(),
270
+ unsupportedStoredDocuments: z.enum(["refuse", "read-only"]).optional()
271
+ });
272
+ const runnerKindSchema = z.enum(["reactor", "compound"]);
273
+ /** A compound member's process: its own, or the compound's (`shared`). */
274
+ const memberProcessSchema = z.enum(["own", "shared"]);
275
+ const reactorBackendKindSchema = z.enum([
276
+ "in-process",
277
+ "worker",
278
+ "remote"
279
+ ]);
280
+ const samePath = (a, b) => {
281
+ const norm = (p) => p.replace(/\\/g, "/").replace(/\/+$/, "").replace(/^\.\//, "");
282
+ return norm(a) === norm(b);
283
+ };
284
+ /** Compound wiring: the generic compound runner's `config` block.
285
+ * (`projectDrivesIntoConnect` and `drivesPublicBase` were removed in T3: a
286
+ * member consumes another member's drives through `$output` tokens.) */
287
+ const compoundWiringSchema = z.strictObject({
288
+ /** Member start order; must name declared children and agree with the
289
+ * output-token dependencies (resolve/plan.ts). Optional: without it the
290
+ * order is derived from the tokens. Unnamed members start after the named
291
+ * ones, in declaration order. */
292
+ startOrder: z.array(z.string().min(1)).optional(),
293
+ /** Write .ph/run/<host>.json (default true). */
294
+ runtimeRecord: z.boolean().optional(),
295
+ /** Patch the baked CSP for the runtime registry on a served Connect
296
+ * member (forwarded as `runner.cspRegistrySync` to every member whose
297
+ * runner is `@powerhousedao/ph-cli/runners/connect`). */
298
+ cspRegistrySync: z.boolean().optional()
299
+ });
300
+ /** `config.startOrder ⊆ keys(children)`, checked where both are visible.
301
+ * Apply it LAST (`.superRefine(refineStartOrder)`) to a runner's final host
302
+ * schema: zod refuses to `.extend()` a refined object. */
303
+ function refineStartOrder(host, ctx) {
304
+ const startOrder = host.config?.startOrder;
305
+ if (!Array.isArray(startOrder)) return;
306
+ const members = Object.keys(host.children);
307
+ startOrder.forEach((name, index) => {
308
+ if (startOrder.indexOf(name) !== index) {
309
+ ctx.addIssue({
310
+ code: "custom",
311
+ path: [
312
+ "config",
313
+ "startOrder",
314
+ index
315
+ ],
316
+ message: `startOrder names "${String(name)}" twice; each member starts once.`
317
+ });
318
+ return;
319
+ }
320
+ if (typeof name === "string" && members.includes(name)) return;
321
+ ctx.addIssue({
322
+ code: "custom",
323
+ path: [
324
+ "config",
325
+ "startOrder",
326
+ index
327
+ ],
328
+ message: `startOrder names "${String(name)}", which is not a member. Members: ${members.join(", ") || "(none)"}.`
329
+ });
330
+ });
331
+ }
332
+ const ALLOW_TOKENS = {
333
+ any: tokenable,
334
+ env: envTokenable
335
+ };
336
+ const FORBID_TOKENS = {
337
+ any: (schema) => z.union([schema]),
338
+ env: (schema) => z.union([schema])
339
+ };
340
+ /** The replacement a non-drive `remote.url` message names. */
341
+ function useDriveUrl(host = "switchboard", member) {
342
+ 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"] } } }`;
343
+ }
344
+ /** The `$output` of a declared `remote.url` that reads `endpoints.graphql`. */
345
+ function endpointsGraphqlRef(url) {
346
+ if (typeof url !== "object" || url === null || !("$output" in url)) return;
347
+ const ref = url.$output;
348
+ if (typeof ref !== "object" || ref === null) return void 0;
349
+ const { host, member, path } = ref;
350
+ if (typeof host !== "string" || !Array.isArray(path)) return void 0;
351
+ if (path.join(".") !== "endpoints.graphql") return void 0;
352
+ return {
353
+ host,
354
+ ...typeof member === "string" ? { member } : {}
355
+ };
356
+ }
357
+ /** The slug a drive link names: a `drives.<slug>.url` token's slug or a
358
+ * literal address's served slug; undefined when only runtime knows it. */
359
+ function linkedSlug(url) {
360
+ if (typeof url === "string") return switchboardOfDrive(url)?.slug;
361
+ const ref = typeof url === "object" && url !== null && "$output" in url ? url.$output : void 0;
362
+ const path = Array.isArray(ref?.path) ? ref.path : [];
363
+ return path.length === 3 && path[0] === "drives" && typeof path[1] === "string" && path[2] === "url" ? path[1] : void 0;
364
+ }
365
+ /** The drives a declared host names (home drives, `reactor.drives`, plugin
366
+ * `config.drive` links), or undefined when one is known only at runtime. */
367
+ function knownDriveSlugs(host) {
368
+ const reactor = host.reactor ?? {};
369
+ const slugs = [];
370
+ for (const backend of Object.values(reactor.backends ?? {})) {
371
+ if (backend.kind !== "remote") continue;
372
+ const slug = linkedSlug(backend.remote?.url);
373
+ if (slug === void 0) return void 0;
374
+ slugs.push(slug);
375
+ }
376
+ if (reactor.drives !== void 0) {
377
+ if (!Array.isArray(reactor.drives)) return void 0;
378
+ for (const drive of reactor.drives) if (typeof drive.slug === "string") slugs.push(drive.slug);
379
+ }
380
+ const plugins = Array.isArray(host.runner?.plugins) ? host.runner.plugins : [];
381
+ for (const entry of plugins) {
382
+ const config = typeof entry === "object" && entry !== null && "config" in entry ? entry.config : void 0;
383
+ if (typeof config !== "object" || config === null) continue;
384
+ if (!("drive" in config) || config.drive === void 0) continue;
385
+ const slug = linkedSlug(config.drive);
386
+ if (slug === void 0) return void 0;
387
+ slugs.push(slug);
388
+ }
389
+ for (const drive of connectDefaultDrives(host.config)) {
390
+ if (typeof drive !== "object" || drive === null || !("url" in drive)) continue;
391
+ const slug = linkedSlug(drive.url);
392
+ if (slug === void 0) return void 0;
393
+ slugs.push(slug);
394
+ }
395
+ return slugs;
396
+ }
397
+ /** A Connect host's `config.drives.defaultDrives`, unchecked. */
398
+ function connectDefaultDrives(config) {
399
+ const drives = typeof config === "object" && config !== null && "drives" in config ? config.drives : void 0;
400
+ const list = typeof drives === "object" && drives !== null && "defaultDrives" in drives ? drives.defaultDrives : void 0;
401
+ return Array.isArray(list) ? list : [];
402
+ }
403
+ /** Declared form, at host level so plugin drives are seen: a placement key
404
+ * must name a drive the host names, when every drive is knowable. A host
405
+ * with no remote backend is not checked: its plugins may contribute drives
406
+ * (a switchboard's workflows drive) that no field names. */
407
+ function refineDeclaredPlacementKeys(host, ctx) {
408
+ const placed = Object.keys(host.reactor?.placement?.drives ?? {});
409
+ if (placed.length === 0) return;
410
+ if (!Object.values(host.reactor?.backends ?? {}).some((b) => b.kind === "remote")) return;
411
+ const known = knownDriveSlugs(host);
412
+ if (!known) return;
413
+ const names = (slug, served) => served === slug || served.startsWith(`${slug}-`) && /^[0-9a-f]{8}$/.test(served.slice(slug.length + 1));
414
+ for (const slug of placed) {
415
+ if (known.some((served) => names(slug, served))) continue;
416
+ ctx.addIssue({
417
+ code: "custom",
418
+ path: [
419
+ "reactor",
420
+ "placement",
421
+ "drives",
422
+ slug
423
+ ],
424
+ message: `placement.drives.${slug} names no drive this host links to or declares (${[...new Set(known)].join(", ") || "none"}).`
425
+ });
426
+ }
427
+ }
428
+ /** Resolved-form checks across backends, drives and placement: one base is
429
+ * one remote backend, and a drive placed on a remote is on its switchboard. */
430
+ function refineResolvedReactor(reactor, ctx) {
431
+ const backends = reactor.backends ?? {};
432
+ const baseOf = /* @__PURE__ */ new Map();
433
+ const byBase = /* @__PURE__ */ new Map();
434
+ const linked = /* @__PURE__ */ new Map();
435
+ const link = (slug, base) => linked.set(slug, (linked.get(slug) ?? /* @__PURE__ */ new Set()).add(base));
436
+ for (const [name, backend] of Object.entries(backends)) {
437
+ const url = backend.remote?.url;
438
+ if (backend.kind !== "remote" || typeof url !== "string") continue;
439
+ const home = switchboardOfDrive(url);
440
+ if (!home) continue;
441
+ baseOf.set(name, home.base);
442
+ link(home.slug, home.base);
443
+ const first = byBase.get(home.base);
444
+ if (first === void 0) {
445
+ byBase.set(home.base, name);
446
+ continue;
447
+ }
448
+ ctx.addIssue({
449
+ code: "custom",
450
+ path: [
451
+ "backends",
452
+ name,
453
+ "remote",
454
+ "url"
455
+ ],
456
+ 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.`
457
+ });
458
+ }
459
+ const kept = /* @__PURE__ */ new Set();
460
+ (Array.isArray(reactor.drives) ? reactor.drives : []).forEach((drive, index) => {
461
+ if (!drive.remote) {
462
+ kept.add(drive.slug);
463
+ return;
464
+ }
465
+ const at = switchboardOfDrive(drive.remote.url);
466
+ if (at || drive.remote.url === "") {
467
+ if (at) link(drive.slug, at.base);
468
+ return;
469
+ }
470
+ ctx.addIssue({
471
+ code: "custom",
472
+ path: [
473
+ "drives",
474
+ index,
475
+ "remote",
476
+ "url"
477
+ ],
478
+ 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"] } }.`
479
+ });
480
+ });
481
+ const nameOf = (base) => byBase.get(base) ?? base;
482
+ for (const [slug, name] of Object.entries(reactor.placement?.drives ?? {})) {
483
+ const at = [
484
+ "placement",
485
+ "drives",
486
+ slug
487
+ ];
488
+ const on = [...linked.get(slug) ?? []];
489
+ if (on.length > 0 && kept.has(slug)) {
490
+ ctx.addIssue({
491
+ code: "custom",
492
+ path: at,
493
+ message: `Drive "${slug}" is both this reactor's own drive and on ${on.map(nameOf).join(" and ")}. Rename one, or link only one.`
494
+ });
495
+ continue;
496
+ }
497
+ if (on.length > 1) {
498
+ ctx.addIssue({
499
+ code: "custom",
500
+ path: at,
501
+ message: `Drive "${slug}" is on both ${on.map(nameOf).join(" and ")}. Rename one, or link only one.`
502
+ });
503
+ continue;
504
+ }
505
+ const base = baseOf.get(name);
506
+ if (base === void 0) continue;
507
+ if (on.length === 0) {
508
+ if (!kept.has(slug)) continue;
509
+ ctx.addIssue({
510
+ code: "custom",
511
+ path: at,
512
+ 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.`
513
+ });
514
+ continue;
515
+ }
516
+ if (on[0] === base) continue;
517
+ ctx.addIssue({
518
+ code: "custom",
519
+ path: at,
520
+ 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.`
521
+ });
522
+ }
523
+ }
524
+ /** `remote` keys that tune a connection, so only a remote backend has them. */
525
+ const REMOTE_ONLY_KEYS = [
526
+ "requestTimeoutMs",
527
+ "breaker",
528
+ "realtime"
529
+ ];
530
+ /**
531
+ * Builds the host schema set. "allow" (declared form) accepts `T | Token` in
532
+ * every token-able field; "forbid" (resolved form) accepts `T` only.
533
+ */
534
+ function buildHostSchemas(tokenField) {
535
+ const resolved = tokenField === FORBID_TOKENS;
536
+ const reactorBackendSchema = z.strictObject({
537
+ kind: reactorBackendKindSchema,
538
+ storage: z.strictObject({
539
+ kind: z.enum([
540
+ "idb",
541
+ "memory",
542
+ "path",
543
+ "postgres"
544
+ ]),
545
+ /** `"${userData}/…"` sugar or `{ $env: "NAME" }`. */
546
+ dataDir: tokenField.env(z.string()).optional(),
547
+ url: z.string().optional()
548
+ }).optional(),
549
+ readModel: z.strictObject({ url: z.string().optional() }).optional(),
550
+ packages: z.strictObject({
551
+ cdnUrl: z.string().optional(),
552
+ specs: z.array(z.string()).optional(),
553
+ /** on-demand model resolution (was DYNAMIC_MODEL_LOADING). */
554
+ dynamic: z.boolean().optional()
555
+ }).optional(),
556
+ remote: z.strictObject({
557
+ url: tokenField.any(originOrUrlSchema),
558
+ /** Give up on one request to this switchboard after this long. Default 30_000. */
559
+ requestTimeoutMs: z.number().int().positive().optional(),
560
+ /** After `failures` failed requests in a row, send nothing for
561
+ * `openMs`. Default { failures: 3, openMs: 30_000 }. `false`:
562
+ * never stop trying. */
563
+ breaker: z.union([z.literal(false), z.strictObject({
564
+ failures: z.number().int().min(1).optional(),
565
+ openMs: z.number().int().nonnegative().optional()
566
+ })]).optional(),
567
+ /** Live updates over a socket (the router's GraphQL
568
+ * subscriptions, not drive sync). Default true. */
569
+ realtime: z.boolean().optional()
570
+ }).optional()
571
+ }).superRefine((backend, ctx) => {
572
+ if (backend.kind === "remote" && !backend.remote) ctx.addIssue({
573
+ code: "custom",
574
+ path: ["remote", "url"],
575
+ message: `a "remote" backend needs remote.url, a switchboard drive address: ${useDriveUrl()}.`
576
+ });
577
+ if (backend.kind !== "remote" && backend.remote) for (const key of REMOTE_ONLY_KEYS) {
578
+ if (backend.remote[key] === void 0) continue;
579
+ ctx.addIssue({
580
+ code: "custom",
581
+ path: ["remote", key],
582
+ message: `remote.${key} applies only to a "remote" backend; this one is "${backend.kind}".`
583
+ });
584
+ }
585
+ const url = backend.remote?.url;
586
+ const graphqlRef = resolved ? void 0 : endpointsGraphqlRef(url);
587
+ if (graphqlRef) ctx.addIssue({
588
+ code: "custom",
589
+ path: ["remote", "url"],
590
+ 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)}.`
591
+ });
592
+ if (resolved && typeof url === "string" && !switchboardOfDrive(url)) ctx.addIssue({
593
+ code: "custom",
594
+ path: ["remote", "url"],
595
+ message: `remote.url must be a switchboard drive address (<switchboard>/d/<slug>), not ${url}: sync needs the drive. Use ${useDriveUrl()}.`
596
+ });
597
+ const store = backend.storage;
598
+ const storeDir = store?.kind === "path" ? store.dataDir : void 0;
599
+ const readModel = backend.readModel?.url;
600
+ if (typeof storeDir === "string" && readModel && samePath(storeDir, readModel)) ctx.addIssue({
601
+ code: "custom",
602
+ path: ["readModel", "url"],
603
+ 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.`
604
+ });
605
+ });
606
+ const reactorSchema = z.strictObject({
607
+ backends: z.record(z.string(), reactorBackendSchema).optional(),
608
+ placement: z.strictObject({
609
+ primary: z.string().optional(),
610
+ /** Declared drive slug → backend name. A local backend keeps a
611
+ * synced copy; the drive's own remote backend opens it there with
612
+ * no copy. An unlisted drive keeps a synced copy. */
613
+ drives: z.record(z.string().min(1), z.string().min(1)).optional(),
614
+ /** The backend new drives (and documents outside a drive) are
615
+ * created on. A switchboard keeps no copy in this browser.
616
+ * Default: the browser reactor, else the only switchboard. */
617
+ newDrives: z.string().min(1).optional()
618
+ }).optional(),
619
+ router: z.strictObject({
620
+ /** Wait this long for a reactor to say whether it holds a
621
+ * document. 0: no bound. Default 3_000. */
622
+ probeTimeoutMs: z.number().int().nonnegative().optional(),
623
+ /** Look again after this long for a document found on a later
624
+ * backend. Default 30_000. */
625
+ provisionalRouteMs: z.number().int().nonnegative().optional()
626
+ }).optional(),
627
+ protocol: reactorProtocolSchema.optional(),
628
+ renown: z.strictObject({
629
+ url: z.string().optional(),
630
+ networkId: z.string().optional(),
631
+ chainId: z.number().int().optional()
632
+ }).optional(),
633
+ namespace: z.string().min(1).optional(),
634
+ drives: tokenField.any(z.array(buildDriveDeclarationSchema(tokenField.any))).optional()
635
+ }).superRefine((reactor, ctx) => {
636
+ const backends = reactor.backends ?? {};
637
+ for (const [slug, name] of Object.entries(reactor.placement?.drives ?? {})) {
638
+ if (Object.hasOwn(backends, name)) continue;
639
+ ctx.addIssue({
640
+ code: "custom",
641
+ path: [
642
+ "placement",
643
+ "drives",
644
+ slug
645
+ ],
646
+ message: `placement.drives.${slug} names backend "${name}", which is not in backends (${Object.keys(backends).join(", ") || "none"}).`
647
+ });
648
+ }
649
+ const newDrives = reactor.placement?.newDrives;
650
+ if (newDrives !== void 0 && !Object.hasOwn(backends, newDrives)) ctx.addIssue({
651
+ code: "custom",
652
+ path: ["placement", "newDrives"],
653
+ message: `placement.newDrives names backend "${newDrives}", which is not in backends (${Object.keys(backends).join(", ") || "none"}).`
654
+ });
655
+ if (resolved) refineResolvedReactor(reactor, ctx);
656
+ });
657
+ /** Common runner options; runner modules extend it with their own. */
658
+ const runnerBaseSchema = z.looseObject({
659
+ module: z.string().min(1),
660
+ defaultVerb: z.string().min(1).optional(),
661
+ port: z.number().int().positive().optional(),
662
+ /** Bind address; each runner documents its default. */
663
+ host: z.string().min(1).optional(),
664
+ /** THE COMPOSITION: plugin entries; presence is activation. */
665
+ plugins: z.array(pluginEntrySchema).optional()
666
+ });
667
+ /** A compound member wrapper. Sections are FULL STATEMENTS except `runner`,
668
+ * which key-merges over the member's own. Plugins live in `runner.plugins`
669
+ * (as on a standalone host); there is no wrapper-level `plugins`. */
670
+ const childWrapperSchema = z.strictObject({
671
+ host: z.string().min(1).regex(HOST_REF_PATTERN, HOST_REF_MESSAGE),
672
+ runner: runnerBaseSchema.partial().extend({ port: z.number().int().min(0).max(65535).optional() }).optional(),
673
+ config: z.looseObject({}).optional(),
674
+ reactor: reactorSchema.optional(),
675
+ /** Where the member runs: `own`, a child process of the compound
676
+ * (`ph run <host>`), stopped through its stdin; `shared`, in the
677
+ * compound's own process. Default: `own` next to a foreground member
678
+ * (the Cli runner), `shared` otherwise. */
679
+ process: memberProcessSchema.optional()
680
+ });
681
+ const childrenSchema = z.record(z.string(), childWrapperSchema);
682
+ return {
683
+ reactorBackendSchema,
684
+ reactorSchema,
685
+ runnerBaseSchema,
686
+ childWrapperSchema,
687
+ childrenSchema,
688
+ reactorHostSchema: z.strictObject({
689
+ name: hostNameSchema,
690
+ runner: runnerBaseSchema,
691
+ config: z.looseObject({}).optional(),
692
+ profile: profileSchema.optional(),
693
+ reactor: reactorSchema.optional()
694
+ }),
695
+ compoundHostSchema: z.strictObject({
696
+ name: hostNameSchema,
697
+ runner: runnerBaseSchema,
698
+ children: childrenSchema,
699
+ config: z.looseObject({}).optional(),
700
+ profile: profileSchema.optional()
701
+ }),
702
+ /** This set's field wrapper, for a runner's OWN token-able fields inside
703
+ * `defineHostSchemas`: declared, `T | Token` in and `T` out; resolved,
704
+ * `T` only. Both modes share one static type. */
705
+ tokenable: tokenField.any,
706
+ /** As `tokenable`, but the only token accepted is `$env`. */
707
+ envTokenable: tokenField.env
708
+ };
709
+ }
710
+ /** The host schema set in declared ("allow": token-able fields take tokens)
711
+ * or resolved ("forbid") form. */
712
+ function makeHostSchemas(options) {
713
+ return buildHostSchemas(options.tokens === "allow" ? ALLOW_TOKENS : FORBID_TOKENS);
714
+ }
715
+ /** The issues a host-level refinement raises, outside a zod parse. */
716
+ function collectIssues(host, refine) {
717
+ if (typeof host !== "object" || host === null || !("reactor" in host)) return [];
718
+ const issues = [];
719
+ refine(host, { addIssue: (issue) => {
720
+ issues.push({
721
+ path: (issue.path ?? []).filter((part) => typeof part !== "symbol"),
722
+ message: issue.message ?? ""
723
+ });
724
+ } });
725
+ return issues;
726
+ }
727
+ /** withPlacementKeys' check, for a merged declared host parsed some other way. */
728
+ function placementKeyIssues(host) {
729
+ return collectIssues(host, refineDeclaredPlacementKeys);
730
+ }
731
+ const CONNECT_PRIMARY_MESSAGE = "Connect doesn't use placement.primary. To choose where new drives go, use placement.newDrives.";
732
+ /**
733
+ * A Connect host's placement rules, in either form. The router's primary is
734
+ * the browser reactor, else the `newDrives` switchboard, else the only one,
735
+ * so `placement.primary` means nothing here, and a Connect with several
736
+ * switchboards and no browser reactor must say where new drives go. Apply it
737
+ * last to the Connect runner's schema: `.superRefine(refineConnectReactor)`.
738
+ */
739
+ function refineConnectReactor(host, ctx) {
740
+ const reactor = host.reactor;
741
+ if (!reactor) return;
742
+ if (reactor.placement?.primary !== void 0) ctx.addIssue({
743
+ code: "custom",
744
+ path: [
745
+ "reactor",
746
+ "placement",
747
+ "primary"
748
+ ],
749
+ message: CONNECT_PRIMARY_MESSAGE
750
+ });
751
+ const backends = Object.entries(reactor.backends ?? {});
752
+ const remotes = backends.filter(([, backend]) => backend.kind === "remote").map(([name]) => name);
753
+ if (remotes.length > 1 && remotes.length === backends.length && reactor.placement?.newDrives === void 0) ctx.addIssue({
754
+ code: "custom",
755
+ path: [
756
+ "reactor",
757
+ "placement",
758
+ "newDrives"
759
+ ],
760
+ message: `This Connect keeps no reactor in the browser and links ${remotes.length} switchboards (${remotes.join(", ")}). Set placement.newDrives to the one new drives are created on.`
761
+ });
762
+ }
763
+ /** refineConnectReactor's check, for a Connect host parsed some other way. */
764
+ function connectReactorIssues(host) {
765
+ return collectIssues(host, refineConnectReactor);
766
+ }
767
+ /** Adds the host-level placement key check to a runner's declared schema. */
768
+ function withPlacementKeys(schema) {
769
+ if (!(schema instanceof z.ZodType)) return schema;
770
+ return schema.superRefine((host, ctx) => {
771
+ if (typeof host === "object" && host !== null && "reactor" in host) refineDeclaredPlacementKeys(host, ctx);
772
+ });
773
+ }
774
+ /**
775
+ * One runner definition, two schemas (3.5): `build` runs over the DECLARED
776
+ * set (tokens allowed; its z.input types host files) and the RESOLVED set
777
+ * (no tokens; `validateHost` checks it before the verb). Export both, type
778
+ * the host as `z.input<typeof declaredHostSchema>`, refine last inside the
779
+ * builder (zod can't extend a refined object), and wrap the runner's own
780
+ * token-able fields with `s.tokenable` / `s.envTokenable`.
781
+ */
782
+ function defineHostSchemas(build) {
783
+ return {
784
+ declaredHostSchema: withPlacementKeys(build(declaredSchemas)),
785
+ hostSchema: build(resolvedSchemas)
786
+ };
787
+ }
788
+ const declaredSchemas = makeHostSchemas({ tokens: "allow" });
789
+ const resolvedSchemas = makeHostSchemas({ tokens: "forbid" });
790
+ const declaredHostSchemas = declaredSchemas;
791
+ const reactorBackendSchema = resolvedSchemas.reactorBackendSchema;
792
+ const reactorSchema = resolvedSchemas.reactorSchema;
793
+ const runnerBaseSchema = resolvedSchemas.runnerBaseSchema;
794
+ const childWrapperSchema = resolvedSchemas.childWrapperSchema;
795
+ const childrenSchema = resolvedSchemas.childrenSchema;
796
+ const reactorHostSchema = resolvedSchemas.reactorHostSchema;
797
+ const compoundHostSchema = resolvedSchemas.compoundHostSchema;
798
+ /** The generic compound runner's host: the base with its wiring config. */
799
+ const genericCompound = defineHostSchemas((s) => s.compoundHostSchema.extend({ config: compoundWiringSchema.optional() }).superRefine(refineStartOrder));
800
+ const genericCompoundHostSchema = genericCompound.hostSchema;
801
+ const declaredGenericCompoundHostSchema = genericCompound.declaredHostSchema;
802
+ const SCHEMA_BASE = "https://powerhouse.inc/schemas";
803
+ /** One host schema as an editor JSON Schema with a stable `$id` — the
804
+ * per-runner emission helper (runner packages emit their own hostSchema). */
805
+ function emitHostJsonSchema(name, schema) {
806
+ return {
807
+ $id: `${SCHEMA_BASE}/${name}.schema.json`,
808
+ ...z.toJSONSchema(schema, { io: "input" })
809
+ };
810
+ }
811
+ /** The emitted-schema set, keyed by published filename. Pure — the
812
+ * emit-schemas script writes these and the drift test re-derives them. */
813
+ function emittedHostSchemas() {
814
+ return {
815
+ "host-reactor.schema.json": emitHostJsonSchema("host-reactor", declaredSchemas.reactorHostSchema),
816
+ "host-compound.schema.json": emitHostJsonSchema("host-compound", declaredSchemas.compoundHostSchema)
817
+ };
818
+ }
819
+ //#endregion
820
+ //#region src/instance-key.ts
821
+ /** The data folder of a project: where its `.ph` tree is. */
822
+ function instanceDataDir(projectDir = process.cwd(), env = process.env) {
823
+ return path.resolve(env.PH_USER_DATA_DIR ?? projectDir);
824
+ }
825
+ /** The key of `host` (a record key, see `runRecordKey`) in a project. */
826
+ function instanceKey(host, projectDir = process.cwd(), env = process.env) {
827
+ const dataDir = instanceDataDir(projectDir, env);
828
+ return {
829
+ host,
830
+ dataDir,
831
+ id: `${host}@${process.platform === "win32" ? dataDir.toLowerCase() : dataDir}`
832
+ };
833
+ }
834
+ /** The `.ph` tree of a data folder. */
835
+ function instancePhDir(key) {
836
+ return path.join(key.dataDir, ".ph");
837
+ }
838
+ /** Where the run records of a data folder are: the one place they are kept. */
839
+ function instanceRunDir(key) {
840
+ return path.join(instancePhDir(key), "run");
841
+ }
842
+ /** Where a Cli keeps the state of its services: under the data folder, so
843
+ * two project folders never see each other's. */
844
+ function instanceServicesDir(key, cliName) {
845
+ return path.join(instancePhDir(key), cliName, "services");
846
+ }
847
+ //#endregion
848
+ //#region src/run-record-schema.ts
849
+ /**
850
+ * `.ph/run/<host>.json`, version 2 (typed-host-configs 3.6): what a running
851
+ * host and its members produced. Validated on read; a v1 (or any invalid)
852
+ * record reads as "not running". `projectName` is kept beyond the plan's
853
+ * sketch because the live/foreign probe needs it. `host` is the host's
854
+ * `name` (the file key), not its folder. A host an installed package
855
+ * supplies has its record in a folder named after the package,
856
+ * `.ph/run/<package>/<host>.json`, and says which in `package`.
857
+ */
858
+ const outputsSchema = z.record(z.string(), z.unknown());
859
+ const runRecordMemberSchema = z.strictObject({
860
+ /** The member's host as the project addresses it: its folder, or
861
+ * `<package>/<host>` for one a package supplies. */
862
+ host: z.string().min(1),
863
+ runnerModule: z.string().min(1),
864
+ kind: runnerKindSchema,
865
+ verb: z.string().min(1),
866
+ outputs: outputsSchema
867
+ });
868
+ const runRecordSchema = z.strictObject({
869
+ version: z.literal(2),
870
+ host: hostNameSchema,
871
+ /** The installed package that supplies the host; absent for the
872
+ * project's own. */
873
+ package: z.string().regex(PACKAGE_NAME_PATTERN).optional(),
874
+ projectName: z.string(),
875
+ kind: runnerKindSchema,
876
+ verb: z.string().min(1),
877
+ pid: z.number().int(),
878
+ startedAt: z.string(),
879
+ /** Standalone hosts: the runner's outputs. */
880
+ outputs: outputsSchema.optional(),
881
+ /** Compounds: one entry per started member, keyed by member name. */
882
+ members: z.record(z.string(), runRecordMemberSchema).optional(),
883
+ /** Host-specific extras (e.g. mcpUrl) a runner wants in the record. */
884
+ extra: z.record(z.string(), z.unknown()).optional()
885
+ });
886
+ //#endregion
887
+ //#region src/run-record.ts
888
+ /** The key a host's record is filed under: its `name`, behind the package
889
+ * that supplies it when it is not the project's own (`@acme/tools/studio`),
890
+ * as `ph run` addresses the host. */
891
+ function runRecordKey(name, hostPackage) {
892
+ return hostPackage === void 0 ? name : `${hostPackage}/${name}`;
893
+ }
894
+ /** The key of a record as read: where it is filed. */
895
+ function recordKeyOf(record) {
896
+ return runRecordKey(record.host, record.package);
897
+ }
898
+ const runDir = (projectDir, env = process.env) => instanceRunDir(instanceKey("", projectDir, env));
899
+ /** The file of an instance's record: `(host, data folder)` is its path. */
900
+ function runRecordPath(projectDir, key, env) {
901
+ return recordPath(projectDir, key, env);
902
+ }
903
+ function recordPath(projectDir, key, env) {
904
+ const dir = runDir(projectDir, env);
905
+ const slash = key.lastIndexOf("/");
906
+ const hostName = key.slice(slash + 1);
907
+ const pkg = slash === -1 ? void 0 : key.slice(0, slash);
908
+ const folder = pkg === void 0 ? path.resolve(dir) : path.resolve(dir, ...pkg.split("/"));
909
+ const file = path.resolve(folder, `${hostName}.json`);
910
+ if (!hostNameSchema.safeParse(hostName).success || pkg !== void 0 && !PACKAGE_NAME_PATTERN.test(pkg) || path.dirname(file) !== folder) throw new Error(`"${key}" can't name a run record. ${HOST_NAME_MESSAGE}`);
911
+ return file;
912
+ }
913
+ /** The record keys under `.ph/run/`: `<name>.json` files, and those in a
914
+ * package's folder (`<pkg>/` or `@scope/<pkg>/`). */
915
+ function recordKeys(dir) {
916
+ const entries = (at) => {
917
+ try {
918
+ return fs.readdirSync(at, { withFileTypes: true });
919
+ } catch {
920
+ return [];
921
+ }
922
+ };
923
+ const records = (at, prefix) => entries(at).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => `${prefix}${entry.name.slice(0, -5)}`);
924
+ const keys = records(dir, "");
925
+ for (const entry of entries(dir)) {
926
+ if (!entry.isDirectory()) continue;
927
+ const at = path.join(dir, entry.name);
928
+ if (!entry.name.startsWith("@")) {
929
+ keys.push(...records(at, `${entry.name}/`));
930
+ continue;
931
+ }
932
+ for (const inner of entries(at)) {
933
+ if (!inner.isDirectory()) continue;
934
+ keys.push(...records(path.join(at, inner.name), `${entry.name}/${inner.name}/`));
935
+ }
936
+ }
937
+ return keys;
938
+ }
939
+ function readRunRecord(projectDir, hostName, env = process.env) {
940
+ let raw;
941
+ try {
942
+ raw = JSON.parse(fs.readFileSync(recordPath(projectDir, hostName, env), "utf8"));
943
+ } catch {
944
+ return;
945
+ }
946
+ const parsed = runRecordSchema.safeParse(raw);
947
+ return parsed.success ? parsed.data : void 0;
948
+ }
949
+ /** Every valid v2 record under `.ph/run/`, package hosts' included (invalid
950
+ * and v1 files skipped). */
951
+ function listRunRecords(projectDir, env = process.env) {
952
+ return recordKeys(runDir(projectDir, env)).flatMap((key) => {
953
+ const record = readRunRecord(projectDir, key, env);
954
+ return record ? [record] : [];
955
+ });
956
+ }
957
+ /** The project identity the live/foreign probe compares: package.json
958
+ * `name`, else the folder name. */
959
+ function readProjectName(projectDir) {
960
+ try {
961
+ const pkg = JSON.parse(fs.readFileSync(path.join(projectDir, "package.json"), "utf8"));
962
+ if (typeof pkg.name === "string" && pkg.name) return pkg.name;
963
+ } catch {}
964
+ return path.basename(path.resolve(projectDir));
965
+ }
966
+ function writeRunRecord(projectDir, record) {
967
+ const target = recordPath(projectDir, recordKeyOf(record));
968
+ const valid = runRecordSchema.parse(record);
969
+ fs.mkdirSync(path.dirname(target), { recursive: true });
970
+ const text = `${JSON.stringify(valid, null, 2)}\n`;
971
+ if (valid.extra?.control === void 0 && valid.extra?.signIn === void 0) {
972
+ fs.writeFileSync(target, text);
973
+ return;
974
+ }
975
+ writeOwnerOnlyFile(target, text);
976
+ }
977
+ function clearRunRecord(projectDir, hostName, env = process.env) {
978
+ try {
979
+ fs.rmSync(recordPath(projectDir, hostName, env));
980
+ } catch {}
981
+ }
982
+ function isPidAlive(pid) {
983
+ try {
984
+ process.kill(pid, 0);
985
+ return true;
986
+ } catch (error) {
987
+ return error.code === "EPERM";
988
+ }
989
+ }
990
+ /** When a process started, in ms since the epoch; undefined when the
991
+ * platform does not tell (the process is gone, the tool is missing). */
992
+ function processStartedAtMs(pid) {
993
+ try {
994
+ if (process.platform === "linux") {
995
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
996
+ const ticks = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]);
997
+ const boot = /^btime (\d+)$/m.exec(fs.readFileSync("/proc/stat", "utf8"));
998
+ if (!boot || !Number.isFinite(ticks)) return void 0;
999
+ return (Number(boot[1]) + ticks / 100) * 1e3;
1000
+ }
1001
+ const [command, args] = process.platform === "win32" ? ["powershell.exe", [
1002
+ "-NoProfile",
1003
+ "-NonInteractive",
1004
+ "-Command",
1005
+ `(Get-Process -Id ${pid}).StartTime.ToUniversalTime().ToString('o')`
1006
+ ]] : ["ps", [
1007
+ "-o",
1008
+ "lstart=",
1009
+ "-p",
1010
+ String(pid)
1011
+ ]];
1012
+ const out = execFileSync(command, args, {
1013
+ encoding: "utf8",
1014
+ stdio: [
1015
+ "ignore",
1016
+ "pipe",
1017
+ "ignore"
1018
+ ],
1019
+ timeout: 1e4,
1020
+ windowsHide: true,
1021
+ env: {
1022
+ ...process.env,
1023
+ LC_ALL: "C"
1024
+ }
1025
+ }).trim();
1026
+ const started = Date.parse(out);
1027
+ return Number.isFinite(started) ? started : void 0;
1028
+ } catch {
1029
+ return;
1030
+ }
1031
+ }
1032
+ const START_SLACK_MS = 5e3;
1033
+ const confirmedRecords = /* @__PURE__ */ new Set();
1034
+ /** True when the recorded pid now names another process: one that started
1035
+ * after the record was written. False when that cannot be told. */
1036
+ function isPidReused(record) {
1037
+ if (record.pid === process.pid) return false;
1038
+ const recordedAt = Date.parse(record.startedAt);
1039
+ if (!Number.isFinite(recordedAt)) return false;
1040
+ const key = `${record.pid}:${record.startedAt}`;
1041
+ if (confirmedRecords.has(key)) return false;
1042
+ const startedAt = processStartedAtMs(record.pid);
1043
+ if (startedAt === void 0) return false;
1044
+ if (startedAt > recordedAt + START_SLACK_MS) return true;
1045
+ confirmedRecords.add(key);
1046
+ return false;
1047
+ }
1048
+ /**
1049
+ * Decide whether the recorded instance is this project's live host.
1050
+ *
1051
+ * pid liveness alone proves nothing (pids are reused): a live pid counts
1052
+ * only when its process started before the record was written. The recorded
1053
+ * projectName is what separates "my instance" from "a different project that
1054
+ * happens to hold this storage root" — the confusion the vetra lock exists to
1055
+ * prevent. A stale record (dead or reused pid) is reported so the caller can
1056
+ * clear it; a foreign one (live pid, different project) is left alone.
1057
+ */
1058
+ function probeRun(projectDir, hostName, projectName, env = process.env) {
1059
+ const record = readRunRecord(projectDir, hostName, env);
1060
+ if (!record) return { status: "none" };
1061
+ if (!isPidAlive(record.pid) || isPidReused(record)) return {
1062
+ status: "stale",
1063
+ record
1064
+ };
1065
+ if (record.projectName !== projectName) return {
1066
+ status: "foreign",
1067
+ record
1068
+ };
1069
+ return {
1070
+ status: "live",
1071
+ record
1072
+ };
1073
+ }
1074
+ //#endregion
1075
+ export { refineStartOrder as $, childWrapperSchema as A, mapTokenSchema as At, genericCompoundHostSchema as B, CONNECT_PRIMARY_MESSAGE as C, envTokenSchema as Ct, HOST_REF_MESSAGE as D, isToken as Dt, HOST_NAME_PATTERN as E, forbidRef as Et, declaredGenericCompoundHostSchema as F, tokenable as Ft, placementKeyIssues as G, makeHostSchemas as H, declaredHostSchemas as I, reactorBackendSchema as J, profileSchema as K, defineHostSchemas as L, compoundHostSchema as M, ref as Mt, compoundWiringSchema as N, tokenKeyOf as Nt, HOST_REF_PATTERN as O, itemTokenSchema as Ot, connectReactorIssues as P, tokenSchema as Pt, refineConnectReactor as Q, emitHostJsonSchema as R, instanceServicesDir as S, concatTokenSchema as St, HOST_NAME_MESSAGE as T, findToken as Tt, memberProcessSchema as U, hostNameSchema as V, originOrUrlSchema as W, reactorProtocolSchema as X, reactorHostSchema as Y, reactorSchema as Z, writeOwnerOnlyFile as _, driveDeclarationSchema as _t, processStartedAtMs as a, mergeContributions as at, instancePhDir as b, TOKEN_ESCAPE_KEY as bt, recordKeyOf as c, pluginEntryObjectSchema as ct, writeRunRecord as d, resolveOrder as dt, runnerBaseSchema as et, runRecordMemberSchema as f, runObserveHook as ft, restrictFileToOwner as g, buildDriveDeclarationSchema as gt, fileAccessList as h, runTransformHook as ht, probeRun as i, hostTypeSatisfies as it, childrenSchema as j, outputTokenSchema as jt, PACKAGE_NAME_PATTERN as k, keyTokenSchema as kt, runRecordKey as l, pluginEntrySchema as lt, createOwnerOnlyFile as m, runProvideHook as mt, isPidAlive as n, PluginError as nt, readProjectName as o, normalizePluginEntries as ot, runRecordSchema as p, runObserveHookSequential as pt, reactorBackendKindSchema as q, listRunRecords as r, entryActiveForVerb as rt, readRunRecord as s, normalizePluginEntry as st, clearRunRecord as t, runnerKindSchema as tt, runRecordPath as u, registerHostType as ut, instanceDataDir as v, drivesSchema as vt, HOST_NAME_MAX_LENGTH as w, envTokenable as wt, instanceRunDir as x, TOKEN_KEYS as xt, instanceKey as y, projectDriveIdWith as yt, emittedHostSchemas as z };
1076
+
1077
+ //# sourceMappingURL=run-record-C6oTZF_C.mjs.map