@powerhousedao/host-core 6.4.0-next.2 → 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
@@ -1,4 +1,7 @@
1
+ import { F as declaredGenericCompoundHostSchema, Nt as tokenKeyOf, Pt as tokenSchema, Tt as findToken, bt as TOKEN_ESCAPE_KEY, c as recordKeyOf, d as writeRunRecord, i as probeRun, it as hostTypeSatisfies, k as PACKAGE_NAME_PATTERN, l as runRecordKey, n as isPidAlive, nt as PluginError, ot as normalizePluginEntries, r as listRunRecords, rt as entryActiveForVerb, t as clearRunRecord, tt as runnerKindSchema } from "./run-record-C6oTZF_C.mjs";
1
2
  import { closeProcessControlChannel, controlRecordOf, ensureProcessControlChannel } from "./control-channel.mjs";
3
+ import { describeInstance, instanceOfRecord, runningInstance } from "./instance.mjs";
4
+ import { a as STOP_ON_STDIN_ENV, r as resolvePhCliEntry, t as childEnv } from "./host-entry-B8n_590_.mjs";
2
5
  import { killTree } from "./kill-tree.mjs";
3
6
  import { createRequire } from "node:module";
4
7
  import { createHash } from "node:crypto";
@@ -7,54 +10,9 @@ import path from "node:path";
7
10
  import { pathToFileURL } from "node:url";
8
11
  import { Worker } from "node:worker_threads";
9
12
  import { z } from "zod";
10
- 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";
11
- import { isOriginPlaceholderUrl } from "@powerhousedao/shared/connect/origin-placeholder";
13
+ import { spawn } from "node:child_process";
14
+ import { LOCAL_SIGN_IN_SECRET_ENV, newSignInSecret, openInBrowser, opensBrowser, signInLink } from "@powerhousedao/shared/clis/local-sign-in";
12
15
  import { resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
13
- import { execFileSync, spawn } from "node:child_process";
14
- import net from "node:net";
15
- //#region src/drive-schema.ts
16
- /**
17
- * The schema half of drives.ts, zod only so `./schema` stays neutral.
18
- * - slug: the SEEDING KEY (idempotence); id optional (stable identity).
19
- * - preferredEditor: stored at header.meta.preferredEditor; Connect config's
20
- * `app` is the legacy alias.
21
- * - remote.url: a drive served elsewhere; local fields are ignored for it.
22
- * Token-able (`$output` on a producer's `drives.<slug>.url`).
23
- */
24
- function buildDriveDeclarationSchema(urlField) {
25
- return z.strictObject({
26
- slug: z.string().min(1),
27
- id: z.string().min(1).optional(),
28
- /** Derive the id from the project path (`<slug>-<hash of the path>`) — the
29
- * same ids classic `ph vetra` produced. `true` serves the drive under the
30
- * hashed slug too (the vetra drive's slug IS its hashed id); `"id"` hashes
31
- * only the id and keeps the declared slug (the classic Workflows drive:
32
- * `/d/workflows`, id `workflows-<hash>`). */
33
- projectHash: z.union([z.boolean(), z.literal("id")]).optional(),
34
- /** What a missing drive is created as. Default powerhouse/document-drive. */
35
- documentType: z.enum(["powerhouse/document-drive", "powerhouse/reactor-drive"]).optional(),
36
- name: z.string().min(1).optional(),
37
- icon: z.string().optional(),
38
- preferredEditor: z.string().optional(),
39
- sharingType: z.enum([
40
- "public",
41
- "private",
42
- "shared"
43
- ]).optional(),
44
- availableOffline: z.boolean().optional(),
45
- remote: z.strictObject({ url: urlField(z.string().min(1)) }).optional()
46
- });
47
- }
48
- const driveDeclarationSchema = buildDriveDeclarationSchema(tokenable);
49
- const drivesSchema = z.array(driveDeclarationSchema);
50
- /** The project-hashed drive id (`${slug}-${sha256(projectRoot)[0..8]}`) with
51
- * the hash function injected, so neutral consumers (a browser monitor) can
52
- * pass `crypto.subtle`-derived or precomputed hex. drives.ts binds it to
53
- * node:crypto as `projectDriveId`. */
54
- function projectDriveIdWith(sha256Hex, projectRoot, slug) {
55
- return `${slug}-${sha256Hex(projectRoot).substring(0, 8)}`;
56
- }
57
- //#endregion
58
16
  //#region src/connect-composition.ts
59
17
  /**
60
18
  * The connect config slices each built-in Connect plugin owns, by specifier
@@ -190,775 +148,6 @@ function defaultConnectComposition(config) {
190
148
  return composition;
191
149
  }
192
150
  //#endregion
193
- //#region src/plugins.ts
194
- /**
195
- * R1 — the host plugin framework (bridge-runners-to-plugins plan,
196
- * customization-references/host-core as the blueprint).
197
- *
198
- * A plugin is hooks + contributions; hooks are boot wiring (main realm only),
199
- * contributions are declarative, serializable surface. Host RUNTIMES define
200
- * the hook vocabulary and interleave their own wiring between stages — they
201
- * are never plugins themselves.
202
- *
203
- * host.js carries the COMPOSITION as `runner.plugins` entries:
204
- * string | { module, enabled?, verbs?, config? }
205
- * Presence is activation (enabled defaults true); `verbs` scopes an entry to
206
- * matching run verbs; `config` is validated against the plugin's declared
207
- * zod schema. Entries resolve from the PROJECT's dependency tree exactly
208
- * like runner modules.
209
- */
210
- var PluginError = class extends Error {
211
- constructor(message, hint) {
212
- super(hint ? `${message}\n Hint: ${hint}` : message);
213
- this.name = "PluginError";
214
- }
215
- };
216
- const pluginEntryObjectSchema = z.strictObject({
217
- module: z.string().min(1),
218
- /** Presence is activation BY DEFAULT; false is the explicit off-switch. */
219
- enabled: z.boolean().optional(),
220
- /** "*" (default) or the run verbs this entry is active for. */
221
- verbs: z.union([z.literal("*"), z.array(z.string().min(1)).min(1)]).optional(),
222
- /** Validated against the plugin's declared configSchema at resolution. */
223
- config: z.record(z.string(), z.unknown()).optional()
224
- });
225
- const pluginEntrySchema = z.union([z.string().min(1), pluginEntryObjectSchema]);
226
- function normalizePluginEntry(entry) {
227
- if (typeof entry === "string") return {
228
- module: entry,
229
- enabled: true,
230
- verbs: "*",
231
- config: {}
232
- };
233
- return {
234
- module: entry.module,
235
- enabled: entry.enabled ?? true,
236
- verbs: entry.verbs ?? "*",
237
- config: entry.config ?? {}
238
- };
239
- }
240
- /** Module is the identity key: a duplicate makes override targeting and
241
- * ordering ambiguous, so it fails loudly. */
242
- function normalizePluginEntries(entries, where) {
243
- const normalized = entries.map(normalizePluginEntry);
244
- const seen = /* @__PURE__ */ new Set();
245
- for (const entry of normalized) {
246
- 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.");
247
- seen.add(entry.module);
248
- }
249
- return normalized;
250
- }
251
- function entryActiveForVerb(entry, verb) {
252
- if (!entry.enabled) return false;
253
- return entry.verbs === "*" || entry.verbs.includes(verb);
254
- }
255
- /**
256
- * The appliesTo hierarchy. "reactor" is the base every reactor host extends;
257
- * "compound" is its own branch (plugins over the member set — e.g. the clint
258
- * proxy). Host runtimes register their id with a parent; compatibility walks
259
- * the parent chain.
260
- */
261
- const HOST_TYPE_PARENTS = {
262
- reactor: null,
263
- compound: null,
264
- connect: "reactor",
265
- switchboard: "reactor",
266
- mastra: "reactor"
267
- };
268
- function registerHostType(id, parent) {
269
- 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])}".`);
270
- HOST_TYPE_PARENTS[id] = parent;
271
- }
272
- function hostTypeSatisfies(hostType, appliesTo) {
273
- let current = hostType;
274
- while (current !== null) {
275
- if (current === appliesTo) return true;
276
- current = current in HOST_TYPE_PARENTS ? HOST_TYPE_PARENTS[current] : null;
277
- }
278
- return false;
279
- }
280
- /** Registration order, bucketed pre → normal → post (stable within buckets),
281
- * then dependsOn topo-sorted within the bucketed order. */
282
- function resolveOrder(plugins) {
283
- const buckets = {
284
- pre: [],
285
- normal: [],
286
- post: []
287
- };
288
- for (const plugin of plugins) buckets[plugin.enforce ?? "normal"].push(plugin);
289
- const bucketed = [
290
- ...buckets.pre,
291
- ...buckets.normal,
292
- ...buckets.post
293
- ];
294
- const byName = new Map(bucketed.map((p) => [p.name, p]));
295
- 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.");
296
- const ordered = [];
297
- const state = /* @__PURE__ */ new Map();
298
- const visit = (plugin, chain) => {
299
- const mark = state.get(plugin.name);
300
- if (mark === "done") return;
301
- if (mark === "visiting") throw new PluginError(`Plugin dependency cycle: ${[...chain, plugin.name].join(" -> ")}.`);
302
- state.set(plugin.name, "visiting");
303
- for (const dep of plugin.dependsOn ?? []) visit(byName.get(dep), [...chain, plugin.name]);
304
- state.set(plugin.name, "done");
305
- ordered.push(plugin);
306
- };
307
- for (const plugin of bucketed) visit(plugin, []);
308
- return ordered;
309
- }
310
- async function runProvideHook(name, plugins, ctx) {
311
- const impls = plugins.filter((p) => typeof p.hooks?.[name] === "function");
312
- if (impls.length > 1) throw new PluginError(`Hook "${name}" is provided by ${impls.map((p) => `"${p.name}"`).join(" and ")} — provide hooks have one winner.`);
313
- const impl = impls[0]?.hooks?.[name];
314
- return impl ? await impl(ctx) : void 0;
315
- }
316
- async function runTransformHook(name, plugins, ctx, seed) {
317
- let value = seed;
318
- for (const plugin of plugins) {
319
- const impl = plugin.hooks?.[name];
320
- if (typeof impl === "function") value = await impl(value, ctx);
321
- }
322
- return value;
323
- }
324
- /** Sequential observe, in plugin order — for lifecycle moments whose order
325
- * is load-bearing (teardown: the switchboard stops privacy before workflows
326
- * before the api, per the carve map). */
327
- async function runObserveHookSequential(name, plugins, ctx) {
328
- for (const plugin of plugins) {
329
- const impl = plugin.hooks?.[name];
330
- if (typeof impl === "function") await impl(ctx);
331
- }
332
- }
333
- async function runObserveHook(name, plugins, ctx) {
334
- await Promise.all(plugins.map(async (plugin) => {
335
- const impl = plugin.hooks?.[name];
336
- if (typeof impl === "function") await impl(ctx);
337
- }));
338
- }
339
- /** Array kinds concatenate in provenance-then-order sequence (built-in first,
340
- * so later sources read as overrides where consumers want last-wins). */
341
- function mergeContributions(resolved) {
342
- const rank = {
343
- "built-in": 0,
344
- local: 1,
345
- dependency: 2
346
- };
347
- const sorted = [...resolved].sort((a, b) => rank[a.provenance] - rank[b.provenance]);
348
- const merged = {};
349
- for (const { plugin, provenance } of sorted) for (const [kind, values] of Object.entries(plugin.contributions ?? {})) {
350
- if (!values) continue;
351
- const bucket = merged[kind] ??= [];
352
- for (const value of values) bucket.push({
353
- value,
354
- source: {
355
- pluginName: plugin.name,
356
- provenance
357
- }
358
- });
359
- }
360
- return merged;
361
- }
362
- //#endregion
363
- //#region src/host-schemas.ts
364
- /**
365
- * The zod single source for host.js blocks (typed-host-configs G1). Every
366
- * host type is z.input/z.output of these schemas; nothing is hand-mirrored.
367
- * Top-level host objects and the `reactor` block are STRICT (a typo fails);
368
- * `runner` stays loose until each runner declares its options (T2), and
369
- * `config` is runner-defined.
370
- *
371
- * Token-able fields (typed-host-configs 3.5): `reactor.backends.*.remote.url`
372
- * (required, a switchboard drive address), `reactor.drives` (whole list, e.g. `$map`),
373
- * `reactor.drives[].remote.url` and `storage.dataDir` (`$env` only). Their z.input admits tokens, their z.output is the resolved type.
374
- */
375
- /** A host's `name` keys its run record, `.ph/run/<name>.json`, so it must be
376
- * one safe path segment. */
377
- const HOST_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
378
- const HOST_NAME_MAX_LENGTH = 128;
379
- 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.";
380
- const hostNameSchema = z.string().min(1).max(128, HOST_NAME_MESSAGE).regex(HOST_NAME_PATTERN, HOST_NAME_MESSAGE);
381
- /** An npm package name, as `<package>/<host>` names a package that supplies
382
- * hosts: `name` or `@scope/name`, each part letters, digits, '-', '.', '_'
383
- * and '~', not starting with '.' or '_'. Each part is one folder name, the
384
- * one the package has under node_modules. */
385
- const PACKAGE_NAME_PATTERN = /^(?:@[A-Za-z0-9~-][A-Za-z0-9._~-]*\/)?[A-Za-z0-9~-][A-Za-z0-9._~-]*$/;
386
- /** How a compound names a member's host: its folder under the project's
387
- * `hosts/` (or, in a package's compound, the package's first), or
388
- * `<package>/<host>` for one an installed package supplies. */
389
- const HOST_REF_PATTERN = new RegExp(`^(?:${PACKAGE_NAME_PATTERN.source.slice(1, -1)}/)?${HOST_NAME_PATTERN.source.slice(1, -1)}$`);
390
- 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.";
391
- /**
392
- * A URL, or one written against the page origin (`${origin}/graphql`): the
393
- * browser resolves the placeholder when it loads Connect's config, for a
394
- * member whose own server proxies the switchboard's paths.
395
- */
396
- const originOrUrlSchema = z.union([z.url(), z.string().refine(isOriginPlaceholderUrl, { message: "a URL, or ${origin}/<path> for a proxied sibling" })]);
397
- const profileSchema = z.strictObject({
398
- appId: z.string().min(1).optional(),
399
- name: z.string().min(1).optional(),
400
- description: z.string().optional(),
401
- icon: z.string().optional()
402
- });
403
- const reactorProtocolSchema = z.strictObject({
404
- featureFlags: z.strictObject({
405
- documentDecisions: z.boolean().optional(),
406
- authEnforcement: z.boolean().optional(),
407
- authGroups: z.boolean().optional(),
408
- authConditions: z.boolean().optional(),
409
- undoV3: z.boolean().optional()
410
- }).optional(),
411
- createSignaturePolicy: z.enum(["legacy", "v2-required"]).optional(),
412
- unsupportedStoredDocuments: z.enum(["refuse", "read-only"]).optional()
413
- });
414
- const runnerKindSchema = z.enum(["reactor", "compound"]);
415
- /** A compound member's process: its own, or the compound's (`shared`). */
416
- const memberProcessSchema = z.enum(["own", "shared"]);
417
- const reactorBackendKindSchema = z.enum([
418
- "in-process",
419
- "worker",
420
- "remote"
421
- ]);
422
- const samePath = (a, b) => {
423
- const norm = (p) => p.replace(/\\/g, "/").replace(/\/+$/, "").replace(/^\.\//, "");
424
- return norm(a) === norm(b);
425
- };
426
- /** Compound wiring: the generic compound runner's `config` block.
427
- * (`projectDrivesIntoConnect` and `drivesPublicBase` were removed in T3: a
428
- * member consumes another member's drives through `$output` tokens.) */
429
- const compoundWiringSchema = z.strictObject({
430
- /** Member start order; must name declared children and agree with the
431
- * output-token dependencies (resolve/plan.ts). Optional: without it the
432
- * order is derived from the tokens. Unnamed members start after the named
433
- * ones, in declaration order. */
434
- startOrder: z.array(z.string().min(1)).optional(),
435
- /** Write .ph/run/<host>.json (default true). */
436
- runtimeRecord: z.boolean().optional(),
437
- /** Patch the baked CSP for the runtime registry on a served Connect
438
- * member (forwarded as `runner.cspRegistrySync` to every member whose
439
- * runner is `@powerhousedao/ph-cli/runners/connect`). */
440
- cspRegistrySync: z.boolean().optional()
441
- });
442
- /** `config.startOrder ⊆ keys(children)`, checked where both are visible.
443
- * Apply it LAST (`.superRefine(refineStartOrder)`) to a runner's final host
444
- * schema: zod refuses to `.extend()` a refined object. */
445
- function refineStartOrder(host, ctx) {
446
- const startOrder = host.config?.startOrder;
447
- if (!Array.isArray(startOrder)) return;
448
- const members = Object.keys(host.children);
449
- startOrder.forEach((name, index) => {
450
- if (startOrder.indexOf(name) !== index) {
451
- ctx.addIssue({
452
- code: "custom",
453
- path: [
454
- "config",
455
- "startOrder",
456
- index
457
- ],
458
- message: `startOrder names "${String(name)}" twice; each member starts once.`
459
- });
460
- return;
461
- }
462
- if (typeof name === "string" && members.includes(name)) return;
463
- ctx.addIssue({
464
- code: "custom",
465
- path: [
466
- "config",
467
- "startOrder",
468
- index
469
- ],
470
- message: `startOrder names "${String(name)}", which is not a member. Members: ${members.join(", ") || "(none)"}.`
471
- });
472
- });
473
- }
474
- const ALLOW_TOKENS = {
475
- any: tokenable,
476
- env: envTokenable
477
- };
478
- const FORBID_TOKENS = {
479
- any: (schema) => z.union([schema]),
480
- env: (schema) => z.union([schema])
481
- };
482
- /** The replacement a non-drive `remote.url` message names. */
483
- function useDriveUrl(host = "switchboard", member) {
484
- 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"] } } }`;
485
- }
486
- /** The `$output` of a declared `remote.url` that reads `endpoints.graphql`. */
487
- function endpointsGraphqlRef(url) {
488
- if (typeof url !== "object" || url === null || !("$output" in url)) return;
489
- const ref = url.$output;
490
- if (typeof ref !== "object" || ref === null) return void 0;
491
- const { host, member, path } = ref;
492
- if (typeof host !== "string" || !Array.isArray(path)) return void 0;
493
- if (path.join(".") !== "endpoints.graphql") return void 0;
494
- return {
495
- host,
496
- ...typeof member === "string" ? { member } : {}
497
- };
498
- }
499
- /** The slug a drive link names: a `drives.<slug>.url` token's slug or a
500
- * literal address's served slug; undefined when only runtime knows it. */
501
- function linkedSlug(url) {
502
- if (typeof url === "string") return switchboardOfDrive(url)?.slug;
503
- const ref = typeof url === "object" && url !== null && "$output" in url ? url.$output : void 0;
504
- const path = Array.isArray(ref?.path) ? ref.path : [];
505
- return path.length === 3 && path[0] === "drives" && typeof path[1] === "string" && path[2] === "url" ? path[1] : void 0;
506
- }
507
- /** The drives a declared host names (home drives, `reactor.drives`, plugin
508
- * `config.drive` links), or undefined when one is known only at runtime. */
509
- function knownDriveSlugs(host) {
510
- const reactor = host.reactor ?? {};
511
- const slugs = [];
512
- for (const backend of Object.values(reactor.backends ?? {})) {
513
- if (backend.kind !== "remote") continue;
514
- const slug = linkedSlug(backend.remote?.url);
515
- if (slug === void 0) return void 0;
516
- slugs.push(slug);
517
- }
518
- if (reactor.drives !== void 0) {
519
- if (!Array.isArray(reactor.drives)) return void 0;
520
- for (const drive of reactor.drives) if (typeof drive.slug === "string") slugs.push(drive.slug);
521
- }
522
- const plugins = Array.isArray(host.runner?.plugins) ? host.runner.plugins : [];
523
- for (const entry of plugins) {
524
- const config = typeof entry === "object" && entry !== null && "config" in entry ? entry.config : void 0;
525
- if (typeof config !== "object" || config === null) continue;
526
- if (!("drive" in config) || config.drive === void 0) continue;
527
- const slug = linkedSlug(config.drive);
528
- if (slug === void 0) return void 0;
529
- slugs.push(slug);
530
- }
531
- for (const drive of connectDefaultDrives(host.config)) {
532
- if (typeof drive !== "object" || drive === null || !("url" in drive)) continue;
533
- const slug = linkedSlug(drive.url);
534
- if (slug === void 0) return void 0;
535
- slugs.push(slug);
536
- }
537
- return slugs;
538
- }
539
- /** A Connect host's `config.drives.defaultDrives`, unchecked. */
540
- function connectDefaultDrives(config) {
541
- const drives = typeof config === "object" && config !== null && "drives" in config ? config.drives : void 0;
542
- const list = typeof drives === "object" && drives !== null && "defaultDrives" in drives ? drives.defaultDrives : void 0;
543
- return Array.isArray(list) ? list : [];
544
- }
545
- /** Declared form, at host level so plugin drives are seen: a placement key
546
- * must name a drive the host names, when every drive is knowable. A host
547
- * with no remote backend is not checked: its plugins may contribute drives
548
- * (a switchboard's workflows drive) that no field names. */
549
- function refineDeclaredPlacementKeys(host, ctx) {
550
- const placed = Object.keys(host.reactor?.placement?.drives ?? {});
551
- if (placed.length === 0) return;
552
- if (!Object.values(host.reactor?.backends ?? {}).some((b) => b.kind === "remote")) return;
553
- const known = knownDriveSlugs(host);
554
- if (!known) return;
555
- const names = (slug, served) => served === slug || served.startsWith(`${slug}-`) && /^[0-9a-f]{8}$/.test(served.slice(slug.length + 1));
556
- for (const slug of placed) {
557
- if (known.some((served) => names(slug, served))) continue;
558
- ctx.addIssue({
559
- code: "custom",
560
- path: [
561
- "reactor",
562
- "placement",
563
- "drives",
564
- slug
565
- ],
566
- message: `placement.drives.${slug} names no drive this host links to or declares (${[...new Set(known)].join(", ") || "none"}).`
567
- });
568
- }
569
- }
570
- /** Resolved-form checks across backends, drives and placement: one base is
571
- * one remote backend, and a drive placed on a remote is on its switchboard. */
572
- function refineResolvedReactor(reactor, ctx) {
573
- const backends = reactor.backends ?? {};
574
- const baseOf = /* @__PURE__ */ new Map();
575
- const byBase = /* @__PURE__ */ new Map();
576
- const linked = /* @__PURE__ */ new Map();
577
- const link = (slug, base) => linked.set(slug, (linked.get(slug) ?? /* @__PURE__ */ new Set()).add(base));
578
- for (const [name, backend] of Object.entries(backends)) {
579
- const url = backend.remote?.url;
580
- if (backend.kind !== "remote" || typeof url !== "string") continue;
581
- const home = switchboardOfDrive(url);
582
- if (!home) continue;
583
- baseOf.set(name, home.base);
584
- link(home.slug, home.base);
585
- const first = byBase.get(home.base);
586
- if (first === void 0) {
587
- byBase.set(home.base, name);
588
- continue;
589
- }
590
- ctx.addIssue({
591
- code: "custom",
592
- path: [
593
- "backends",
594
- name,
595
- "remote",
596
- "url"
597
- ],
598
- 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.`
599
- });
600
- }
601
- const kept = /* @__PURE__ */ new Set();
602
- (Array.isArray(reactor.drives) ? reactor.drives : []).forEach((drive, index) => {
603
- if (!drive.remote) {
604
- kept.add(drive.slug);
605
- return;
606
- }
607
- const at = switchboardOfDrive(drive.remote.url);
608
- if (at || drive.remote.url === "") {
609
- if (at) link(drive.slug, at.base);
610
- return;
611
- }
612
- ctx.addIssue({
613
- code: "custom",
614
- path: [
615
- "drives",
616
- index,
617
- "remote",
618
- "url"
619
- ],
620
- 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"] } }.`
621
- });
622
- });
623
- const nameOf = (base) => byBase.get(base) ?? base;
624
- for (const [slug, name] of Object.entries(reactor.placement?.drives ?? {})) {
625
- const at = [
626
- "placement",
627
- "drives",
628
- slug
629
- ];
630
- const on = [...linked.get(slug) ?? []];
631
- if (on.length > 0 && kept.has(slug)) {
632
- ctx.addIssue({
633
- code: "custom",
634
- path: at,
635
- message: `Drive "${slug}" is both this reactor's own drive and on ${on.map(nameOf).join(" and ")}. Rename one, or link only one.`
636
- });
637
- continue;
638
- }
639
- if (on.length > 1) {
640
- ctx.addIssue({
641
- code: "custom",
642
- path: at,
643
- message: `Drive "${slug}" is on both ${on.map(nameOf).join(" and ")}. Rename one, or link only one.`
644
- });
645
- continue;
646
- }
647
- const base = baseOf.get(name);
648
- if (base === void 0) continue;
649
- if (on.length === 0) {
650
- if (!kept.has(slug)) continue;
651
- ctx.addIssue({
652
- code: "custom",
653
- path: at,
654
- 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.`
655
- });
656
- continue;
657
- }
658
- if (on[0] === base) continue;
659
- ctx.addIssue({
660
- code: "custom",
661
- path: at,
662
- 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.`
663
- });
664
- }
665
- }
666
- /** `remote` keys that tune a connection, so only a remote backend has them. */
667
- const REMOTE_ONLY_KEYS = [
668
- "requestTimeoutMs",
669
- "breaker",
670
- "realtime"
671
- ];
672
- /**
673
- * Builds the host schema set. "allow" (declared form) accepts `T | Token` in
674
- * every token-able field; "forbid" (resolved form) accepts `T` only.
675
- */
676
- function buildHostSchemas(tokenField) {
677
- const resolved = tokenField === FORBID_TOKENS;
678
- const reactorBackendSchema = z.strictObject({
679
- kind: reactorBackendKindSchema,
680
- storage: z.strictObject({
681
- kind: z.enum([
682
- "idb",
683
- "memory",
684
- "path",
685
- "postgres"
686
- ]),
687
- /** `"${userData}/…"` sugar or `{ $env: "NAME" }`. */
688
- dataDir: tokenField.env(z.string()).optional(),
689
- url: z.string().optional()
690
- }).optional(),
691
- readModel: z.strictObject({ url: z.string().optional() }).optional(),
692
- packages: z.strictObject({
693
- cdnUrl: z.string().optional(),
694
- specs: z.array(z.string()).optional(),
695
- /** on-demand model resolution (was DYNAMIC_MODEL_LOADING). */
696
- dynamic: z.boolean().optional()
697
- }).optional(),
698
- remote: z.strictObject({
699
- url: tokenField.any(originOrUrlSchema),
700
- /** Give up on one request to this switchboard after this long. Default 30_000. */
701
- requestTimeoutMs: z.number().int().positive().optional(),
702
- /** After `failures` failed requests in a row, send nothing for
703
- * `openMs`. Default { failures: 3, openMs: 30_000 }. `false`:
704
- * never stop trying. */
705
- breaker: z.union([z.literal(false), z.strictObject({
706
- failures: z.number().int().min(1).optional(),
707
- openMs: z.number().int().nonnegative().optional()
708
- })]).optional(),
709
- /** Live updates over a socket (the router's GraphQL
710
- * subscriptions, not drive sync). Default true. */
711
- realtime: z.boolean().optional()
712
- }).optional()
713
- }).superRefine((backend, ctx) => {
714
- if (backend.kind === "remote" && !backend.remote) ctx.addIssue({
715
- code: "custom",
716
- path: ["remote", "url"],
717
- message: `a "remote" backend needs remote.url, a switchboard drive address: ${useDriveUrl()}.`
718
- });
719
- if (backend.kind !== "remote" && backend.remote) for (const key of REMOTE_ONLY_KEYS) {
720
- if (backend.remote[key] === void 0) continue;
721
- ctx.addIssue({
722
- code: "custom",
723
- path: ["remote", key],
724
- message: `remote.${key} applies only to a "remote" backend; this one is "${backend.kind}".`
725
- });
726
- }
727
- const url = backend.remote?.url;
728
- const graphqlRef = resolved ? void 0 : endpointsGraphqlRef(url);
729
- if (graphqlRef) ctx.addIssue({
730
- code: "custom",
731
- path: ["remote", "url"],
732
- 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)}.`
733
- });
734
- if (resolved && typeof url === "string" && !switchboardOfDrive(url)) ctx.addIssue({
735
- code: "custom",
736
- path: ["remote", "url"],
737
- message: `remote.url must be a switchboard drive address (<switchboard>/d/<slug>), not ${url}: sync needs the drive. Use ${useDriveUrl()}.`
738
- });
739
- const store = backend.storage;
740
- const storeDir = store?.kind === "path" ? store.dataDir : void 0;
741
- const readModel = backend.readModel?.url;
742
- if (typeof storeDir === "string" && readModel && samePath(storeDir, readModel)) ctx.addIssue({
743
- code: "custom",
744
- path: ["readModel", "url"],
745
- 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.`
746
- });
747
- });
748
- const reactorSchema = z.strictObject({
749
- backends: z.record(z.string(), reactorBackendSchema).optional(),
750
- placement: z.strictObject({
751
- primary: z.string().optional(),
752
- /** Declared drive slug → backend name. A local backend keeps a
753
- * synced copy; the drive's own remote backend opens it there with
754
- * no copy. An unlisted drive keeps a synced copy. */
755
- drives: z.record(z.string().min(1), z.string().min(1)).optional(),
756
- /** The backend new drives (and documents outside a drive) are
757
- * created on. A switchboard keeps no copy in this browser.
758
- * Default: the browser reactor, else the only switchboard. */
759
- newDrives: z.string().min(1).optional()
760
- }).optional(),
761
- router: z.strictObject({
762
- /** Wait this long for a reactor to say whether it holds a
763
- * document. 0: no bound. Default 3_000. */
764
- probeTimeoutMs: z.number().int().nonnegative().optional(),
765
- /** Look again after this long for a document found on a later
766
- * backend. Default 30_000. */
767
- provisionalRouteMs: z.number().int().nonnegative().optional()
768
- }).optional(),
769
- protocol: reactorProtocolSchema.optional(),
770
- renown: z.strictObject({
771
- url: z.string().optional(),
772
- networkId: z.string().optional(),
773
- chainId: z.number().int().optional()
774
- }).optional(),
775
- namespace: z.string().min(1).optional(),
776
- drives: tokenField.any(z.array(buildDriveDeclarationSchema(tokenField.any))).optional()
777
- }).superRefine((reactor, ctx) => {
778
- const backends = reactor.backends ?? {};
779
- for (const [slug, name] of Object.entries(reactor.placement?.drives ?? {})) {
780
- if (Object.hasOwn(backends, name)) continue;
781
- ctx.addIssue({
782
- code: "custom",
783
- path: [
784
- "placement",
785
- "drives",
786
- slug
787
- ],
788
- message: `placement.drives.${slug} names backend "${name}", which is not in backends (${Object.keys(backends).join(", ") || "none"}).`
789
- });
790
- }
791
- const newDrives = reactor.placement?.newDrives;
792
- if (newDrives !== void 0 && !Object.hasOwn(backends, newDrives)) ctx.addIssue({
793
- code: "custom",
794
- path: ["placement", "newDrives"],
795
- message: `placement.newDrives names backend "${newDrives}", which is not in backends (${Object.keys(backends).join(", ") || "none"}).`
796
- });
797
- if (resolved) refineResolvedReactor(reactor, ctx);
798
- });
799
- /** Common runner options; runner modules extend it with their own. */
800
- const runnerBaseSchema = z.looseObject({
801
- module: z.string().min(1),
802
- defaultVerb: z.string().min(1).optional(),
803
- port: z.number().int().positive().optional(),
804
- /** Bind address; each runner documents its default. */
805
- host: z.string().min(1).optional(),
806
- /** THE COMPOSITION: plugin entries; presence is activation. */
807
- plugins: z.array(pluginEntrySchema).optional()
808
- });
809
- /** A compound member wrapper. Sections are FULL STATEMENTS except `runner`,
810
- * which key-merges over the member's own. Plugins live in `runner.plugins`
811
- * (as on a standalone host); there is no wrapper-level `plugins`. */
812
- const childWrapperSchema = z.strictObject({
813
- host: z.string().min(1).regex(HOST_REF_PATTERN, HOST_REF_MESSAGE),
814
- runner: runnerBaseSchema.partial().extend({ port: z.number().int().min(0).max(65535).optional() }).optional(),
815
- config: z.looseObject({}).optional(),
816
- reactor: reactorSchema.optional(),
817
- /** Where the member runs: `own`, a child process of the compound
818
- * (`ph run <host>`), stopped through its stdin; `shared`, in the
819
- * compound's own process. Default: `own` next to a foreground member
820
- * (the Cli runner), `shared` otherwise. */
821
- process: memberProcessSchema.optional()
822
- });
823
- const childrenSchema = z.record(z.string(), childWrapperSchema);
824
- return {
825
- reactorBackendSchema,
826
- reactorSchema,
827
- runnerBaseSchema,
828
- childWrapperSchema,
829
- childrenSchema,
830
- reactorHostSchema: z.strictObject({
831
- name: hostNameSchema,
832
- runner: runnerBaseSchema,
833
- config: z.looseObject({}).optional(),
834
- profile: profileSchema.optional(),
835
- reactor: reactorSchema.optional()
836
- }),
837
- compoundHostSchema: z.strictObject({
838
- name: hostNameSchema,
839
- runner: runnerBaseSchema,
840
- children: childrenSchema,
841
- config: z.looseObject({}).optional(),
842
- profile: profileSchema.optional()
843
- }),
844
- /** This set's field wrapper, for a runner's OWN token-able fields inside
845
- * `defineHostSchemas`: declared, `T | Token` in and `T` out; resolved,
846
- * `T` only. Both modes share one static type. */
847
- tokenable: tokenField.any,
848
- /** As `tokenable`, but the only token accepted is `$env`. */
849
- envTokenable: tokenField.env
850
- };
851
- }
852
- /** The host schema set in declared ("allow": token-able fields take tokens)
853
- * or resolved ("forbid") form. */
854
- function makeHostSchemas(options) {
855
- return buildHostSchemas(options.tokens === "allow" ? ALLOW_TOKENS : FORBID_TOKENS);
856
- }
857
- /** The issues a host-level refinement raises, outside a zod parse. */
858
- function collectIssues(host, refine) {
859
- if (typeof host !== "object" || host === null || !("reactor" in host)) return [];
860
- const issues = [];
861
- refine(host, { addIssue: (issue) => {
862
- issues.push({
863
- path: (issue.path ?? []).filter((part) => typeof part !== "symbol"),
864
- message: issue.message ?? ""
865
- });
866
- } });
867
- return issues;
868
- }
869
- /** withPlacementKeys' check, for a merged declared host parsed some other way. */
870
- function placementKeyIssues(host) {
871
- return collectIssues(host, refineDeclaredPlacementKeys);
872
- }
873
- const CONNECT_PRIMARY_MESSAGE = "Connect doesn't use placement.primary. To choose where new drives go, use placement.newDrives.";
874
- /**
875
- * A Connect host's placement rules, in either form. The router's primary is
876
- * the browser reactor, else the `newDrives` switchboard, else the only one,
877
- * so `placement.primary` means nothing here, and a Connect with several
878
- * switchboards and no browser reactor must say where new drives go. Apply it
879
- * last to the Connect runner's schema: `.superRefine(refineConnectReactor)`.
880
- */
881
- function refineConnectReactor(host, ctx) {
882
- const reactor = host.reactor;
883
- if (!reactor) return;
884
- if (reactor.placement?.primary !== void 0) ctx.addIssue({
885
- code: "custom",
886
- path: [
887
- "reactor",
888
- "placement",
889
- "primary"
890
- ],
891
- message: CONNECT_PRIMARY_MESSAGE
892
- });
893
- const backends = Object.entries(reactor.backends ?? {});
894
- const remotes = backends.filter(([, backend]) => backend.kind === "remote").map(([name]) => name);
895
- if (remotes.length > 1 && remotes.length === backends.length && reactor.placement?.newDrives === void 0) ctx.addIssue({
896
- code: "custom",
897
- path: [
898
- "reactor",
899
- "placement",
900
- "newDrives"
901
- ],
902
- 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.`
903
- });
904
- }
905
- /** refineConnectReactor's check, for a Connect host parsed some other way. */
906
- function connectReactorIssues(host) {
907
- return collectIssues(host, refineConnectReactor);
908
- }
909
- /** Adds the host-level placement key check to a runner's declared schema. */
910
- function withPlacementKeys(schema) {
911
- if (!(schema instanceof z.ZodType)) return schema;
912
- return schema.superRefine((host, ctx) => {
913
- if (typeof host === "object" && host !== null && "reactor" in host) refineDeclaredPlacementKeys(host, ctx);
914
- });
915
- }
916
- /**
917
- * One runner definition, two schemas (3.5): `build` runs over the DECLARED
918
- * set (tokens allowed; its z.input types host files) and the RESOLVED set
919
- * (no tokens; `validateHost` checks it before the verb). Export both, type
920
- * the host as `z.input<typeof declaredHostSchema>`, refine last inside the
921
- * builder (zod can't extend a refined object), and wrap the runner's own
922
- * token-able fields with `s.tokenable` / `s.envTokenable`.
923
- */
924
- function defineHostSchemas(build) {
925
- return {
926
- declaredHostSchema: withPlacementKeys(build(declaredSchemas)),
927
- hostSchema: build(resolvedSchemas)
928
- };
929
- }
930
- const declaredSchemas = makeHostSchemas({ tokens: "allow" });
931
- const resolvedSchemas = makeHostSchemas({ tokens: "forbid" });
932
- const declaredHostSchemas = declaredSchemas;
933
- const reactorBackendSchema = resolvedSchemas.reactorBackendSchema;
934
- const reactorSchema = resolvedSchemas.reactorSchema;
935
- const runnerBaseSchema = resolvedSchemas.runnerBaseSchema;
936
- const childWrapperSchema = resolvedSchemas.childWrapperSchema;
937
- const childrenSchema = resolvedSchemas.childrenSchema;
938
- const reactorHostSchema = resolvedSchemas.reactorHostSchema;
939
- const compoundHostSchema = resolvedSchemas.compoundHostSchema;
940
- /** The generic compound runner's host: the base with its wiring config. */
941
- const genericCompound = defineHostSchemas((s) => s.compoundHostSchema.extend({ config: compoundWiringSchema.optional() }).superRefine(refineStartOrder));
942
- const genericCompoundHostSchema = genericCompound.hostSchema;
943
- const declaredGenericCompoundHostSchema = genericCompound.declaredHostSchema;
944
- const SCHEMA_BASE = "https://powerhouse.inc/schemas";
945
- /** One host schema as an editor JSON Schema with a stable `$id` — the
946
- * per-runner emission helper (runner packages emit their own hostSchema). */
947
- function emitHostJsonSchema(name, schema) {
948
- return {
949
- $id: `${SCHEMA_BASE}/${name}.schema.json`,
950
- ...z.toJSONSchema(schema, { io: "input" })
951
- };
952
- }
953
- /** The emitted-schema set, keyed by published filename. Pure — the
954
- * emit-schemas script writes these and the drift test re-derives them. */
955
- function emittedHostSchemas() {
956
- return {
957
- "host-reactor.schema.json": emitHostJsonSchema("host-reactor", declaredSchemas.reactorHostSchema),
958
- "host-compound.schema.json": emitHostJsonSchema("host-compound", declaredSchemas.compoundHostSchema)
959
- };
960
- }
961
- //#endregion
962
151
  //#region src/host-ref.ts
963
152
  /**
964
153
  * How a host is addressed (decision D5). A bare name (`switchboard`) is the
@@ -2481,7 +1670,7 @@ function getVerb(runner, specifier, verb) {
2481
1670
  if (typeof candidate !== "function" || !listVerbs(runner).includes(verb)) throw new RunnerError(`Runner "${specifier}" does not support the verb "${verb}". Supported verbs: ${listVerbs(runner).join(", ")}.`);
2482
1671
  return candidate;
2483
1672
  }
2484
- function isRecord$3(value) {
1673
+ function isRecord$4(value) {
2485
1674
  return typeof value === "object" && value !== null && !Array.isArray(value);
2486
1675
  }
2487
1676
  /** reactor XOR children, decided by the runner's declared `kind`. */
@@ -2506,7 +1695,7 @@ function assertKindShape(kind, specifier, host, file) {
2506
1695
  * this runner exports. */
2507
1696
  function knownVerbIssues(runner, specifier, host) {
2508
1697
  const options = host.runner;
2509
- if (!isRecord$3(options)) return [];
1698
+ if (!isRecord$4(options)) return [];
2510
1699
  const verbs = listVerbs(runner);
2511
1700
  const unknownVerb = (verb) => typeof verb === "string" && !verbs.includes(verb);
2512
1701
  const issues = [];
@@ -2515,7 +1704,7 @@ function knownVerbIssues(runner, specifier, host) {
2515
1704
  message: `runner.defaultVerb "${options.defaultVerb}" is not a verb of "${specifier}". Supported verbs: ${verbs.join(", ")}.`
2516
1705
  });
2517
1706
  (Array.isArray(options.plugins) ? options.plugins : []).forEach((entry, index) => {
2518
- if (!isRecord$3(entry) || !Array.isArray(entry.verbs)) return;
1707
+ if (!isRecord$4(entry) || !Array.isArray(entry.verbs)) return;
2519
1708
  const scoped = entry.verbs;
2520
1709
  for (const bad of scoped.filter(unknownVerb)) issues.push({
2521
1710
  path: `runner.plugins[${index}].verbs`,
@@ -2530,7 +1719,7 @@ function formatIssues(issues) {
2530
1719
  function valueAt(host, path) {
2531
1720
  let current = host;
2532
1721
  for (const key of path) if (Array.isArray(current) && typeof key === "number") current = current[key];
2533
- else if (isRecord$3(current) && typeof key === "string") current = current[key];
1722
+ else if (isRecord$4(current) && typeof key === "string") current = current[key];
2534
1723
  else return;
2535
1724
  return current;
2536
1725
  }
@@ -2546,7 +1735,7 @@ function validateHost(runner, specifier, host, file, options = {}) {
2546
1735
  /** What `validateHost` checks, as data: nothing throws. */
2547
1736
  function hostSchemaIssues(runner, schema, specifier, host, options = {}) {
2548
1737
  const issues = [];
2549
- if (isRecord$3(host)) {
1738
+ if (isRecord$4(host)) {
2550
1739
  issues.push(...kindShapeIssues(runner.kind, specifier, host));
2551
1740
  if (options.tokens !== "allow") {
2552
1741
  const token = findToken(host);
@@ -2598,7 +1787,7 @@ function validateDeclaredHost(runner, specifier, host, file, options = {}) {
2598
1787
  const issues = checkTokenSites(host);
2599
1788
  if (options.outputsSchemaOf) issues.push(...checkOutputPaths(host, options.outputsSchemaOf));
2600
1789
  if (issues.length > 0) throw new RunnerError(`${file}: invalid output token:\n${formatIssues(issues)}`);
2601
- if (isRecord$3(host)) assertKindShape(runner.kind, specifier, host, file);
1790
+ if (isRecord$4(host)) assertKindShape(runner.kind, specifier, host, file);
2602
1791
  if (!runner.declaredHostSchema) return;
2603
1792
  parseHost(runner, runner.declaredHostSchema, specifier, host, file, { tokens: "allow" });
2604
1793
  }
@@ -2970,13 +2159,13 @@ function computeOutputsHash(input) {
2970
2159
  function isZodSchema(value) {
2971
2160
  return value !== null && typeof value === "object" && "_zod" in value;
2972
2161
  }
2973
- function isRecord$2(value) {
2162
+ function isRecord$3(value) {
2974
2163
  return value !== null && typeof value === "object" && !Array.isArray(value);
2975
2164
  }
2976
2165
  /** Local (non-remote) slugs from a drive declaration list. */
2977
2166
  function localDriveSlugs(drives) {
2978
2167
  if (!Array.isArray(drives)) return [];
2979
- return drives.flatMap((drive) => isRecord$2(drive) && typeof drive.slug === "string" && drive.remote === void 0 ? [drive.slug] : []);
2168
+ return drives.flatMap((drive) => isRecord$3(drive) && typeof drive.slug === "string" && drive.remote === void 0 ? [drive.slug] : []);
2980
2169
  }
2981
2170
  /**
2982
2171
  * Describes the outputs a host's creation produces, for `ph generate hosts`
@@ -3003,7 +2192,7 @@ async function describeHostOutputs(projectRoot, hostName) {
3003
2192
  unrepresentable: "any"
3004
2193
  });
3005
2194
  const reactor = host.reactor;
3006
- const drives = localDriveSlugs(isRecord$2(reactor) ? reactor.drives : []);
2195
+ const drives = localDriveSlugs(isRecord$3(reactor) ? reactor.drives : []);
3007
2196
  const entries = (host.runner.plugins ?? []).map((entry) => typeof entry === "string" ? entry : {
3008
2197
  ...entry,
3009
2198
  verbs: "*"
@@ -3233,325 +2422,55 @@ function splitCompoundArgv(argv, host, members, foreground) {
3233
2422
  return perMember;
3234
2423
  }
3235
2424
  //#endregion
3236
- //#region src/run-record-schema.ts
3237
- /**
3238
- * `.ph/run/<host>.json`, version 2 (typed-host-configs 3.6): what a running
3239
- * host and its members produced. Validated on read; a v1 (or any invalid)
3240
- * record reads as "not running". `projectName` is kept beyond the plan's
3241
- * sketch because the live/foreign probe needs it. `host` is the host's
3242
- * `name` (the file key), not its folder. A host an installed package
3243
- * supplies has its record in a folder named after the package,
3244
- * `.ph/run/<package>/<host>.json`, and says which in `package`.
3245
- */
3246
- const outputsSchema = z.record(z.string(), z.unknown());
3247
- const runRecordMemberSchema = z.strictObject({
3248
- /** The member's host as the project addresses it: its folder, or
3249
- * `<package>/<host>` for one a package supplies. */
3250
- host: z.string().min(1),
3251
- runnerModule: z.string().min(1),
3252
- kind: runnerKindSchema,
3253
- verb: z.string().min(1),
3254
- outputs: outputsSchema
3255
- });
3256
- const runRecordSchema = z.strictObject({
3257
- version: z.literal(2),
3258
- host: hostNameSchema,
3259
- /** The installed package that supplies the host; absent for the
3260
- * project's own. */
3261
- package: z.string().regex(PACKAGE_NAME_PATTERN).optional(),
3262
- projectName: z.string(),
3263
- kind: runnerKindSchema,
3264
- verb: z.string().min(1),
3265
- pid: z.number().int(),
3266
- startedAt: z.string(),
3267
- /** Standalone hosts: the runner's outputs. */
3268
- outputs: outputsSchema.optional(),
3269
- /** Compounds: one entry per started member, keyed by member name. */
3270
- members: z.record(z.string(), runRecordMemberSchema).optional(),
3271
- /** Host-specific extras (e.g. mcpUrl) a runner wants in the record. */
3272
- extra: z.record(z.string(), z.unknown()).optional()
3273
- });
3274
- //#endregion
3275
- //#region src/run-record.ts
3276
- /** The key a host's record is filed under: its `name`, behind the package
3277
- * that supplies it when it is not the project's own (`@acme/tools/studio`),
3278
- * as `ph run` addresses the host. */
3279
- function runRecordKey(name, hostPackage) {
3280
- return hostPackage === void 0 ? name : `${hostPackage}/${name}`;
3281
- }
3282
- /** The key of a record as read: where it is filed. */
3283
- function recordKeyOf(record) {
3284
- return runRecordKey(record.host, record.package);
3285
- }
3286
- const runDir = (projectDir, env = process.env) => path.join(resolvePhDir(projectDir, env), "run");
3287
- function recordPath(projectDir, key, env) {
3288
- const dir = runDir(projectDir, env);
3289
- const slash = key.lastIndexOf("/");
3290
- const hostName = key.slice(slash + 1);
3291
- const pkg = slash === -1 ? void 0 : key.slice(0, slash);
3292
- const folder = pkg === void 0 ? path.resolve(dir) : path.resolve(dir, ...pkg.split("/"));
3293
- const file = path.resolve(folder, `${hostName}.json`);
3294
- 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}`);
3295
- return file;
3296
- }
3297
- /** The record keys under `.ph/run/`: `<name>.json` files, and those in a
3298
- * package's folder (`<pkg>/` or `@scope/<pkg>/`). */
3299
- function recordKeys(dir) {
3300
- const entries = (at) => {
3301
- try {
3302
- return fs.readdirSync(at, { withFileTypes: true });
3303
- } catch {
3304
- return [];
3305
- }
3306
- };
3307
- const records = (at, prefix) => entries(at).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => `${prefix}${entry.name.slice(0, -5)}`);
3308
- const keys = records(dir, "");
3309
- for (const entry of entries(dir)) {
3310
- if (!entry.isDirectory()) continue;
3311
- const at = path.join(dir, entry.name);
3312
- if (!entry.name.startsWith("@")) {
3313
- keys.push(...records(at, `${entry.name}/`));
3314
- continue;
3315
- }
3316
- for (const inner of entries(at)) {
3317
- if (!inner.isDirectory()) continue;
3318
- keys.push(...records(path.join(at, inner.name), `${entry.name}/${inner.name}/`));
3319
- }
3320
- }
3321
- return keys;
3322
- }
3323
- function readRunRecord(projectDir, hostName, env = process.env) {
3324
- let raw;
3325
- try {
3326
- raw = JSON.parse(fs.readFileSync(recordPath(projectDir, hostName, env), "utf8"));
3327
- } catch {
3328
- return;
3329
- }
3330
- const parsed = runRecordSchema.safeParse(raw);
3331
- return parsed.success ? parsed.data : void 0;
3332
- }
3333
- /** Every valid v2 record under `.ph/run/`, package hosts' included (invalid
3334
- * and v1 files skipped). */
3335
- function listRunRecords(projectDir, env = process.env) {
3336
- return recordKeys(runDir(projectDir, env)).flatMap((key) => {
3337
- const record = readRunRecord(projectDir, key, env);
3338
- return record ? [record] : [];
3339
- });
3340
- }
3341
- /** The project identity the live/foreign probe compares: package.json
3342
- * `name`, else the folder name. */
3343
- function readProjectName(projectDir) {
3344
- try {
3345
- const pkg = JSON.parse(fs.readFileSync(path.join(projectDir, "package.json"), "utf8"));
3346
- if (typeof pkg.name === "string" && pkg.name) return pkg.name;
3347
- } catch {}
3348
- return path.basename(path.resolve(projectDir));
3349
- }
3350
- function writeRunRecord(projectDir, record) {
3351
- const target = recordPath(projectDir, recordKeyOf(record));
3352
- const valid = runRecordSchema.parse(record);
3353
- fs.mkdirSync(path.dirname(target), { recursive: true });
3354
- const text = `${JSON.stringify(valid, null, 2)}\n`;
3355
- if (valid.extra?.control === void 0) {
3356
- fs.writeFileSync(target, text);
3357
- return;
3358
- }
3359
- fs.rmSync(target, { force: true });
3360
- fs.writeFileSync(target, text, { mode: 384 });
3361
- if (process.platform !== "win32") fs.chmodSync(target, 384);
3362
- }
3363
- function clearRunRecord(projectDir, hostName, env = process.env) {
3364
- try {
3365
- fs.rmSync(recordPath(projectDir, hostName, env));
3366
- } catch {}
3367
- }
3368
- function isPidAlive(pid) {
3369
- try {
3370
- process.kill(pid, 0);
3371
- return true;
3372
- } catch (error) {
3373
- return error.code === "EPERM";
3374
- }
3375
- }
3376
- /** When a process started, in ms since the epoch; undefined when the
3377
- * platform does not tell (the process is gone, the tool is missing). */
3378
- function processStartedAtMs(pid) {
3379
- try {
3380
- if (process.platform === "linux") {
3381
- const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
3382
- const ticks = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]);
3383
- const boot = /^btime (\d+)$/m.exec(fs.readFileSync("/proc/stat", "utf8"));
3384
- if (!boot || !Number.isFinite(ticks)) return void 0;
3385
- return (Number(boot[1]) + ticks / 100) * 1e3;
3386
- }
3387
- const [command, args] = process.platform === "win32" ? ["powershell.exe", [
3388
- "-NoProfile",
3389
- "-NonInteractive",
3390
- "-Command",
3391
- `(Get-Process -Id ${pid}).StartTime.ToUniversalTime().ToString('o')`
3392
- ]] : ["ps", [
3393
- "-o",
3394
- "lstart=",
3395
- "-p",
3396
- String(pid)
3397
- ]];
3398
- const out = execFileSync(command, args, {
3399
- encoding: "utf8",
3400
- stdio: [
3401
- "ignore",
3402
- "pipe",
3403
- "ignore"
3404
- ],
3405
- timeout: 1e4,
3406
- windowsHide: true,
3407
- env: {
3408
- ...process.env,
3409
- LC_ALL: "C"
3410
- }
3411
- }).trim();
3412
- const started = Date.parse(out);
3413
- return Number.isFinite(started) ? started : void 0;
3414
- } catch {
3415
- return;
3416
- }
3417
- }
3418
- const START_SLACK_MS = 5e3;
3419
- const confirmedRecords = /* @__PURE__ */ new Set();
3420
- /** True when the recorded pid now names another process: one that started
3421
- * after the record was written. False when that cannot be told. */
3422
- function isPidReused(record) {
3423
- if (record.pid === process.pid) return false;
3424
- const recordedAt = Date.parse(record.startedAt);
3425
- if (!Number.isFinite(recordedAt)) return false;
3426
- const key = `${record.pid}:${record.startedAt}`;
3427
- if (confirmedRecords.has(key)) return false;
3428
- const startedAt = processStartedAtMs(record.pid);
3429
- if (startedAt === void 0) return false;
3430
- if (startedAt > recordedAt + START_SLACK_MS) return true;
3431
- confirmedRecords.add(key);
3432
- return false;
3433
- }
3434
- /**
3435
- * Decide whether the recorded instance is this project's live host.
3436
- *
3437
- * pid liveness alone proves nothing (pids are reused): a live pid counts
3438
- * only when its process started before the record was written. The recorded
3439
- * projectName is what separates "my instance" from "a different project that
3440
- * happens to hold this storage root" — the confusion the vetra lock exists to
3441
- * prevent. A stale record (dead or reused pid) is reported so the caller can
3442
- * clear it; a foreign one (live pid, different project) is left alone.
3443
- */
3444
- function probeRun(projectDir, hostName, projectName, env = process.env) {
3445
- const record = readRunRecord(projectDir, hostName, env);
3446
- if (!record) return { status: "none" };
3447
- if (!isPidAlive(record.pid) || isPidReused(record)) return {
3448
- status: "stale",
3449
- record
3450
- };
3451
- if (record.projectName !== projectName) return {
3452
- status: "foreign",
3453
- record
3454
- };
3455
- return {
3456
- status: "live",
3457
- record
3458
- };
3459
- }
3460
- //#endregion
3461
- //#region src/stop-channel.ts
3462
- /** Set by a supervisor that holds this process's stdin. */
3463
- const STOP_ON_STDIN_ENV = "PH_STOP_ON_STDIN";
2425
+ //#region src/local-sign-in.ts
3464
2426
  /**
3465
- * Windows has no SIGTERM: `process.kill(pid, "SIGTERM")` ends the process at
3466
- * once, so no handler runs and a stack's stores are left as a crash leaves
3467
- * them. A started host therefore listens on a pipe named after its pid, and
3468
- * a connection to it is delivered as the SIGTERM it stands for. Elsewhere
3469
- * the signal itself does this, and there is no channel.
2427
+ * Sign-in by link (F3d), as a stack sees it: the compound makes a secret at
2428
+ * each start, hands it to the members that serve Connect, and keeps it in
2429
+ * its owner-only run record (`extra.signIn`), beside the control channel's
2430
+ * token. Whoever holds the record mints a link with a fresh code: the
2431
+ * compound at start, the Cli of a stack that has one, a second start.
3470
2432
  */
3471
- function stopChannelPath(pid, platform = process.platform) {
3472
- return platform === "win32" ? `\\\\.\\pipe\\ph-stop-${pid}` : void 0;
3473
- }
3474
- /** Calls `onStop` for each connection to `channel`. The server holds no
3475
- * process open, and one that cannot listen leaves the host running without
3476
- * a channel rather than not running. */
3477
- function listenForStop(channel, onStop) {
3478
- const server = net.createServer((socket) => {
3479
- socket.on("error", () => void 0);
3480
- socket.end();
3481
- onStop();
3482
- });
3483
- server.on("error", () => void 0);
3484
- server.listen(channel);
3485
- server.unref();
3486
- return server;
3487
- }
3488
- let installed = false;
3489
- /** What a host's process calls once before it starts anything: from then on
3490
- * {@link requestStop} reaches its SIGTERM handlers on every platform. */
3491
- function installStopChannel() {
3492
- const channel = stopChannelPath(process.pid);
3493
- if (!channel || installed) return;
3494
- installed = true;
3495
- listenForStop(channel, () => {
3496
- if (!process.emit("SIGTERM", "SIGTERM")) process.exit(143);
3497
- });
3498
- }
3499
- const ASK_TIMEOUT_MS = 2e3;
3500
- /** Connects to a stop channel; true once the listener took the request. */
3501
- function askToStop(channel, timeoutMs = ASK_TIMEOUT_MS) {
3502
- return new Promise((resolve) => {
3503
- let connected = false;
3504
- const socket = net.connect(channel);
3505
- socket.setTimeout(timeoutMs, () => socket.destroy());
3506
- socket.once("connect", () => connected = true);
3507
- socket.on("error", () => void 0);
3508
- socket.once("close", () => resolve(connected));
3509
- socket.resume();
2433
+ const isRecord$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2434
+ /** The secret a stack's record keeps, if any. */
2435
+ function signInSecretOf(record) {
2436
+ const signIn = record?.extra?.signIn;
2437
+ return isRecord$2(signIn) && typeof signIn.secret === "string" ? signIn.secret : void 0;
2438
+ }
2439
+ /** The members of a stack that sign pages in by link (their outputs say
2440
+ * `localSignIn`), and their app URLs. */
2441
+ function signInMembersOf(members) {
2442
+ return Object.entries(members).flatMap(([member, entry]) => {
2443
+ const outputs = entry.outputs;
2444
+ if (!isRecord$2(outputs) || !isRecord$2(outputs.localSignIn)) return [];
2445
+ const app = isRecord$2(outputs.endpoints) ? outputs.endpoints.connect : void 0;
2446
+ if (typeof app !== "string") return [];
2447
+ const { open } = outputs.localSignIn;
2448
+ return [{
2449
+ member,
2450
+ app,
2451
+ ...typeof open === "boolean" ? { open } : {}
2452
+ }];
3510
2453
  });
3511
2454
  }
3512
- /**
3513
- * Asks the process to stop as SIGTERM would. False when it could not be
3514
- * asked: on Windows a process without a stop channel (started by an older
3515
- * version, or not a host), which only a kill ends.
3516
- */
3517
- async function requestStop(pid, platform = process.platform) {
3518
- const channel = stopChannelPath(pid, platform);
3519
- if (channel) return askToStop(channel);
3520
- try {
3521
- process.kill(pid, "SIGTERM");
3522
- } catch {}
3523
- return true;
2455
+ /** A fresh link for each member of the stack that signs pages in by link. */
2456
+ function signInLinksOf(record) {
2457
+ const secret = signInSecretOf(record);
2458
+ if (!secret) return [];
2459
+ return signInMembersOf(record.members ?? {}).map(({ member, app, open }) => ({
2460
+ member,
2461
+ link: signInLink(app, secret),
2462
+ ...open === void 0 ? {} : { open }
2463
+ }));
3524
2464
  }
3525
- const STOP_RUN_TIMEOUT_MS = 6e4;
3526
- /** Asks the project's running `hostName` to stop and waits until its process
3527
- * is gone. It never kills: a host that does not answer keeps running. */
3528
- async function stopRun(projectDir, hostName, options = {}) {
3529
- const env = options.env ?? process.env;
3530
- const probe = probeRun(projectDir, hostName, readProjectName(projectDir), env);
3531
- if (probe.status === "none" || probe.status === "stale") return { status: "none" };
3532
- const { pid } = probe.record;
3533
- if (probe.status === "foreign") return {
3534
- status: "foreign",
3535
- pid,
3536
- projectName: probe.record.projectName
3537
- };
3538
- if (!await requestStop(pid)) return {
3539
- status: "unreachable",
3540
- pid
3541
- };
3542
- const deadline = Date.now() + (options.timeoutMs ?? 6e4);
3543
- while (isPidAlive(pid)) {
3544
- if (Date.now() >= deadline) return {
3545
- status: "timeout",
3546
- pid
3547
- };
3548
- await new Promise((resolve) => setTimeout(resolve, 100));
2465
+ /** Prints each link, and opens it as asked, else on a terminal. */
2466
+ function announceSignInLinks(links, open = openInBrowser) {
2467
+ for (const { link, open: asked } of links) {
2468
+ console.log(` ➜ Sign in: ${link}`);
2469
+ if (opensBrowser({
2470
+ asked,
2471
+ isTTY: process.stdout.isTTY
2472
+ })) open(link);
3549
2473
  }
3550
- if (readRunRecord(projectDir, hostName, env)?.pid === pid) clearRunRecord(projectDir, hostName, env);
3551
- return {
3552
- status: "stopped",
3553
- pid
3554
- };
3555
2474
  }
3556
2475
  //#endregion
3557
2476
  //#region src/compound-member.ts
@@ -3695,6 +2614,34 @@ function takeCompoundMember(env, folder) {
3695
2614
  }
3696
2615
  //#endregion
3697
2616
  //#region src/spawn-host.ts
2617
+ const EXISTING_POLL_MS = 500;
2618
+ /** The handle of an instance another start owns: watched, never stopped. */
2619
+ function existingHost(running, dataDir) {
2620
+ const { record } = running;
2621
+ const exit = {
2622
+ code: null,
2623
+ signal: null,
2624
+ forced: false
2625
+ };
2626
+ const exited = new Promise((resolve) => {
2627
+ const timer = setInterval(() => {
2628
+ if (isPidAlive(record.pid)) return;
2629
+ clearInterval(timer);
2630
+ resolve(exit);
2631
+ }, EXISTING_POLL_MS);
2632
+ timer.unref();
2633
+ });
2634
+ return {
2635
+ pid: record.pid,
2636
+ dataDir,
2637
+ record,
2638
+ outputs: record.outputs,
2639
+ members: record.members,
2640
+ existing: true,
2641
+ exited,
2642
+ stop: () => Promise.resolve(exit)
2643
+ };
2644
+ }
3698
2645
  /** The tail line before which a timed-out or aborted run's output is its own. */
3699
2646
  const SPAWN_STOPPING_NOTE = "spawnHost: stopping it";
3700
2647
  var SpawnHostError = class extends Error {
@@ -3713,75 +2660,21 @@ const READY_TIMEOUT_MS = 12e4;
3713
2660
  const STOP_TIMEOUT_MS = 3e4;
3714
2661
  const POLL_MS = 100;
3715
2662
  const CLOSE_WAIT_MS = 1e3;
3716
- const BASE_ENV_KEYS = [
3717
- "PATH",
3718
- "HOME",
3719
- "TMPDIR"
3720
- ];
3721
- const WIN32_ENV_KEYS = [
3722
- "SystemRoot",
3723
- "USERPROFILE",
3724
- "APPDATA",
3725
- "LOCALAPPDATA",
3726
- "TEMP",
3727
- "TMP",
3728
- "ComSpec",
3729
- "PATHEXT"
3730
- ];
3731
- /** The child's whole env: without a `baseEnv`, no other `process.env` key
3732
- * reaches it. */
3733
- function childEnv(dataDir, env = {}, baseEnv) {
3734
- if ("PH_USER_DATA_DIR" in env) throw new Error("spawnHost: set the data dir with `dataDir`, not env.PH_USER_DATA_DIR.");
3735
- if (baseEnv) {
3736
- const base = {};
3737
- for (const [key, value] of Object.entries(baseEnv)) if (value !== void 0) base[key] = value;
3738
- return {
3739
- ...base,
3740
- PH_USER_DATA_DIR: dataDir,
3741
- ...env
3742
- };
3743
- }
3744
- const keys = process.platform === "win32" ? [...BASE_ENV_KEYS, ...WIN32_ENV_KEYS] : BASE_ENV_KEYS;
3745
- const base = {};
3746
- for (const key of keys) {
3747
- const value = process.env[key];
3748
- if (value !== void 0) base[key] = value;
3749
- }
3750
- return {
3751
- ...base,
3752
- PH_USER_DATA_DIR: dataDir,
3753
- PH_NO_TELEMETRY: "1",
3754
- PH_NO_DOTENV: "1",
3755
- ...env
3756
- };
3757
- }
3758
- /** The project's ph-cli, else its ph-run (a packaged app has only that). */
3759
- function resolvePhCliEntry(projectRoot) {
3760
- const require_ = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
3761
- let pkgPath;
3762
- try {
3763
- pkgPath = require_.resolve("@powerhousedao/ph-cli/package.json");
3764
- } catch (error) {
3765
- try {
3766
- pkgPath = require_.resolve("@powerhousedao/ph-run/package.json");
3767
- } catch {
3768
- throw error;
3769
- }
3770
- }
3771
- return path.join(path.dirname(pkgPath), "dist", "cli.mjs");
3772
- }
3773
- /** Readiness waits for a record; refuse a host/verb that writes none. */
2663
+ /** Readiness waits for a record; refuse a host/verb that writes none.
2664
+ * Returns the key of the record it writes. */
3774
2665
  async function assertWritesRecord(projectRoot, host, verb, definition) {
3775
2666
  if (verb !== void 0 && (ONE_SHOT_VERBS.has(verb) || STORE_VERBS.has(verb))) throw new Error(`spawnHost: "${verb}" is a one-shot verb; it writes no run record to wait for.`);
3776
2667
  const declared = definition ?? (await loadHost(projectRoot, host)).host;
3777
2668
  const specifier = declared.runner.module;
3778
2669
  const supplier = locateHost(projectRoot, host).package;
2670
+ const recordKey = runRecordKey(declared.name, supplier?.name);
3779
2671
  const runner = await resolveRunnerModule(supplier?.root ?? projectRoot, specifier);
3780
2672
  if (runner.kind === "compound") {
3781
2673
  if (declared.config?.runtimeRecord === false) throw new Error(`spawnHost: hosts/${host} sets config.runtimeRecord: false, so it writes no run record to wait for.`);
3782
- return;
2674
+ return recordKey;
3783
2675
  }
3784
2676
  if (!isSchemaLike(runner.outputsSchema)) throw new Error(`spawnHost: hosts/${host} runs "${specifier}", which exports no outputsSchema, so it writes no run record to wait for.`);
2677
+ return recordKey;
3785
2678
  }
3786
2679
  const sleep = (ms) => new Promise((resolve) => {
3787
2680
  setTimeout(resolve, ms).unref();
@@ -3821,7 +2714,11 @@ async function spawnHost(options) {
3821
2714
  const stopTimeoutMs = options.stopTimeoutMs ?? STOP_TIMEOUT_MS;
3822
2715
  const { signal, stopOnStdin = false } = options;
3823
2716
  if (signal?.aborted) throw new SpawnHostError("spawnHost: aborted before start.", "aborted", "");
3824
- await assertWritesRecord(projectRoot, options.host, options.verb, options.definition?.host);
2717
+ const recordKey = await assertWritesRecord(projectRoot, options.host, options.verb, options.definition?.host);
2718
+ if (!options.definition) {
2719
+ const running = runningInstance(projectRoot, recordKey, { env: readerEnv });
2720
+ if (running && running.pid !== process.pid) return existingHost(running, dataDir);
2721
+ }
3825
2722
  const cli = options.cli ?? resolvePhCliEntry(projectRoot);
3826
2723
  fs.mkdirSync(dataDir, { recursive: true });
3827
2724
  const log = options.logFile ? fs.createWriteStream(options.logFile, { flags: "a" }) : void 0;
@@ -4192,6 +3089,11 @@ function toStartedHandle(value, where) {
4192
3089
  function takesCspRegistrySync(m) {
4193
3090
  return m.specifier === "@powerhousedao/ph-cli/runners/connect" || declaresKey(m.runner.hostSchema, ["runner"], "cspRegistrySync");
4194
3091
  }
3092
+ /** Whether a member is handed the secret of sign-in by link (F3d): its
3093
+ * runner declares `runner.localSignIn`, or it names the Connect runner. */
3094
+ function takesLocalSignIn(m) {
3095
+ return m.specifier === "@powerhousedao/ph-cli/runners/connect" || declaresKey(m.runner.hostSchema, ["runner"], "localSignIn");
3096
+ }
4195
3097
  /** Past the shell's own limit: this only matters when no shell is left. */
4196
3098
  const STOP_STREAM_LIMIT_MS = 15e3;
4197
3099
  /**
@@ -4360,6 +3262,20 @@ async function runCompound(hostInput, ctx, options) {
4360
3262
  const wiring = host.config ?? {};
4361
3263
  const verb = ctx.verb;
4362
3264
  const oneShotCompound = ONE_SHOT_VERBS.has(verb);
3265
+ const recordKey = runRecordKey(host.name, scope?.name);
3266
+ const probe = oneShotCompound ? void 0 : probeRun(projectRoot, recordKey, options.projectName);
3267
+ const live = probe?.status === "live" ? probe.record : void 0;
3268
+ if (live && (ctx.argv ?? []).length === 0) {
3269
+ const instance = instanceOfRecord(projectRoot, live);
3270
+ console.log(describeInstance(instance));
3271
+ announceSignInLinks(signInLinksOf(live), options.openBrowser);
3272
+ return {
3273
+ started: [],
3274
+ shutdown: () => Promise.resolve(),
3275
+ handleSignal: () => Promise.resolve(),
3276
+ running: instance
3277
+ };
3278
+ }
4363
3279
  let stopRequested = false;
4364
3280
  let stopFromStream = () => {
4365
3281
  stopRequested = true;
@@ -4369,11 +3285,7 @@ async function runCompound(hostInput, ctx, options) {
4369
3285
  const outputs = options.supervisedOutputs ?? [process.stdout, process.stderr];
4370
3286
  for (const output of outputs) output.on("error", () => void 0);
4371
3287
  }
4372
- const recordKey = runRecordKey(host.name, scope?.name);
4373
- const probe = oneShotCompound ? void 0 : probeRun(projectRoot, recordKey, options.projectName);
4374
- const live = probe?.status === "live" ? probe.record : void 0;
4375
3288
  const running = live ? /* @__PURE__ */ new Error(`${recordKey} is already running for this project (pid ${live.pid}). Stop it before starting another.`) : void 0;
4376
- if (running && (ctx.argv ?? []).length === 0) throw running;
4377
3289
  if (probe?.status === "foreign") throw new Error(`.ph/run/${recordKey}.json describes a live "${probe.record.projectName}", but this project is "${options.projectName}". Refusing to start a second instance.`);
4378
3290
  let prepared;
4379
3291
  let order;
@@ -4439,6 +3351,11 @@ async function runCompound(hostInput, ctx, options) {
4439
3351
  host: m.member.host
4440
3352
  }));
4441
3353
  const control = keepsRecord && foreground !== void 0 ? (await ensureProcessControlChannel())?.record : void 0;
3354
+ const signInSecret = keepsRecord && prepared.some(takesLocalSignIn) ? newSignInSecret() : void 0;
3355
+ const envOf = (m) => signInSecret && takesLocalSignIn(m) ? {
3356
+ ...ctx.env,
3357
+ [LOCAL_SIGN_IN_SECRET_ENV]: signInSecret
3358
+ } : ctx.env;
4442
3359
  if (wiring.cspRegistrySync && !prepared.some(takesCspRegistrySync)) console.warn(`${compoundFile}: config.cspRegistrySync is set, but no member's runner declares runner.cspRegistrySync (members run: ${prepared.map((m) => m.specifier).join(", ")}); the baked Connect CSP is not patched for the runtime registry.`);
4443
3360
  const started = [];
4444
3361
  const liveOutputs = /* @__PURE__ */ new Map();
@@ -4510,7 +3427,7 @@ async function runCompound(hostInput, ctx, options) {
4510
3427
  folder: m.ref,
4511
3428
  verb: memberVerb,
4512
3429
  argv,
4513
- env: ctx.env,
3430
+ env: envOf(m),
4514
3431
  host: resolved,
4515
3432
  echo: foreground === void 0,
4516
3433
  ...scope ? { logPackage: scope.name } : {}
@@ -4530,7 +3447,7 @@ async function runCompound(hostInput, ctx, options) {
4530
3447
  handle = toStartedHandle(await fn(oneShot ? emptyMaps(validated, resolved) : validated, {
4531
3448
  projectRoot,
4532
3449
  ...m.hostPackage ? { hostPackage: m.hostPackage } : {},
4533
- env: ctx.env,
3450
+ env: envOf(m),
4534
3451
  verb: memberVerb,
4535
3452
  parent: {
4536
3453
  host: host.name,
@@ -4574,6 +3491,8 @@ async function runCompound(hostInput, ctx, options) {
4574
3491
  await shutdown();
4575
3492
  throw error;
4576
3493
  }
3494
+ const signingIn = signInSecret ? signInMembersOf(Object.fromEntries(started.map((m) => [m.name, m]))) : [];
3495
+ const signIn = signInSecret && signingIn.length > 0 ? { secret: signInSecret } : void 0;
4577
3496
  if (keepsRecord) {
4578
3497
  const recordMembers = {};
4579
3498
  for (const m of started) recordMembers[m.name] = {
@@ -4593,12 +3512,18 @@ async function runCompound(hostInput, ctx, options) {
4593
3512
  pid: process.pid,
4594
3513
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
4595
3514
  members: recordMembers,
4596
- ...options.recordExtra || control ? { extra: {
3515
+ ...options.recordExtra || control || signIn ? { extra: {
4597
3516
  ...options.recordExtra,
4598
- ...control ? { control } : {}
3517
+ ...control ? { control } : {},
3518
+ ...signIn ? { signIn } : {}
4599
3519
  } } : {}
4600
3520
  });
4601
3521
  }
3522
+ if (signIn && foreground === void 0) announceSignInLinks(signingIn.map(({ member, app, open }) => ({
3523
+ member,
3524
+ link: signInLink(app, signIn.secret),
3525
+ ...open === void 0 ? {} : { open }
3526
+ })), options.openBrowser);
4602
3527
  const exit = options.exit ?? ((code) => process.exit(code));
4603
3528
  let ending;
4604
3529
  const end = (code, afterStop) => ending ??= shutdown().finally(() => {
@@ -4717,6 +3642,6 @@ async function memberCycle(projectRoot, prepared) {
4717
3642
  }
4718
3643
  }
4719
3644
  //#endregion
4720
- export { computeOutputsHash as $, runProvideHook as $n, resolveHostPlugins as $t, STOP_RUN_TIMEOUT_MS as A, placementKeyIssues as An, resolveHostOutputs as At, probeRun as B, runnerKindSchema as Bn, checkTokenSites as Bt, applyChildWrapper as C, emitHostJsonSchema as Cn, packageBuildRefusal as Ct, COMPOUND_MEMBER_ENV as D, makeHostSchemas as Dn, TokenResolutionError as Dt, spawnHost as E, hostNameSchema as En, validateHost as Et, stopChannelPath as F, reactorProtocolSchema as Fn, BUILTIN_ENV_NAMES as Ft, writeRunRecord as G, normalizePluginEntries as Gn, schemaAtPath as Gt, readRunRecord as H, entryActiveForVerb as Hn, outputRefsOf as Ht, stopRun as I, reactorSchema as In, isBuiltinEnvName as It, checkRunnerArgv as J, pluginEntrySchema as Jn, formatPath as Jt, runRecordMemberSchema as K, normalizePluginEntry as Kn, collectTokenSites as Kt, clearRunRecord as L, refineConnectReactor as Ln, substituteBuiltinEnv as Lt, installStopChannel as M, reactorBackendKindSchema as Mn, PlanError as Mt, listenForStop as N, reactorBackendSchema as Nn, memberForRef as Nt, takeCompoundMember as O, memberProcessSchema as On, describeMapElements as Ot, requestStop as P, reactorHostSchema as Pn, planCompound as Pt, OUTPUTS_FILE as Q, runObserveHookSequential as Qn, findDeadConnectConfig as Qt, isPidAlive as R, refineStartOrder as Rn, findRemovedForms as Rt, resolveUserDataPlaceholders as S, defineHostSchemas as Sn, tokenable as Sr, listVerbs as St, SpawnHostError as T, genericCompoundHostSchema as Tn, validateDeclaredHost as Tt, recordKeyOf as U, hostTypeSatisfies as Un, outputSitesOf as Ut, readProjectName as V, PluginError as Vn, envSitesOf as Vt, runRecordKey as W, mergeContributions as Wn, refKey as Wt, splitCompoundArgv as X, resolveOrder as Xn, renderTokens as Xt, isRunnerArgsSchema as Y, registerHostType as Yn, isPlainObject as Yt, splitRunArgv as Z, runObserveHook as Zn, unwrapEscapes as Zt, processResolveEnv as _, compoundHostSchema as _n, mapTokenSchema as _r, getVerb as _t, memberProcessOf as a, locateHost as an, drivesSchema as ar, loadHost as at, runnerOutputsSchema as b, declaredGenericCompoundHostSchema as bn, tokenKeyOf as br, kindShapeIssues as bt, prepareMember as c, CONNECT_PRIMARY_MESSAGE as cn, TOKEN_KEYS as cr, probeHostsFolder as ct, takesCspRegistrySync as d, HOST_NAME_PATTERN as dn, envTokenable as dr, stripComments as dt, resolvePluginContributions as en, runTransformHook as er, describeHostOutputs as et, runnerHandleSchema as f, HOST_REF_MESSAGE as fn, findToken as fr, withoutHostsMessage as ft, loadProducers as g, childrenSchema as gn, keyTokenSchema as gr, STORE_VERBS as gt, OUTPUT_DATA_DIRS_ENV as h, childWrapperSchema as hn, itemTokenSchema as hr, RunnerError as ht, memberCycle as i, hostFileLabel as in, driveDeclarationSchema as ir, lintOutputsFile as it, askToStop as j, profileSchema as jn, unsetEnvMessage as jt, STOP_ON_STDIN_ENV as k, originOrUrlSchema as kn, emptyMaps as kt, runCompound as l, HOST_NAME_MAX_LENGTH as ln, concatTokenSchema as lr, readOutputsFileHash as lt, compoundOutputSource as m, PACKAGE_NAME_PATTERN as mn, isToken as mr, ONE_SHOT_VERBS as mt, compoundStartVerb as n, findHostPackage as nn, defaultConnectComposition as nr, lintHostImportGraph as nt, memberVerbOf as o, parseHostRef as on, projectDriveIdWith as or, loadHostFresh as ot, toStartedHandle as p, HOST_REF_PATTERN as pn, forbidRef as pr, CONNECT_RUNNER as pt, runRecordSchema as q, pluginEntryObjectSchema as qn, describeToken as qt, holdStopRequests as r, formatHostRef as rn, buildDriveDeclarationSchema as rr, lintHostImports as rt, planForeground as s, resolvePackageRoot as sn, TOKEN_ESCAPE_KEY as sr, moduleRootOf as st, STOP_STREAM_LIMIT_MS as t, HostLoadError as tn, CONNECT_PLUGIN_OWNED_SLICES as tr, findNonStaticValue as tt, stopStreamOf as u, HOST_NAME_MESSAGE as un, envTokenSchema as ur, scanHostImports as ut, producerOutputsSchemas as v, compoundWiringSchema as vn, outputTokenSchema as vr, hostSchemaIssues as vt, SPAWN_STOPPING_NOTE as w, emittedHostSchemas as wn, resolveRunnerModule as wt, defaultUserDataDir as x, declaredHostSchemas as xn, tokenSchema as xr, knownVerbIssues as xt, runRecordOutputSource as y, connectReactorIssues as yn, ref as yr, isSchemaLike as yt, listRunRecords as z, runnerBaseSchema as zn, checkOutputPaths as zt };
3645
+ export { ONE_SHOT_VERBS as $, signInLinksOf as A, schemaAtPath as At, findNonStaticValue as B, HostLoadError as Bt, applyChildWrapper as C, findRemovedForms as Ct, COMPOUND_MEMBER_ENV as D, outputRefsOf as Dt, spawnHost as E, envSitesOf as Et, splitCompoundArgv as F, renderTokens as Ft, loadHostFresh as G, parseHostRef as Gt, lintHostImports as H, formatHostRef as Ht, splitRunArgv as I, unwrapEscapes as It, readOutputsFileHash as J, defaultConnectComposition as Jt, moduleRootOf as K, resolvePackageRoot as Kt, OUTPUTS_FILE as L, findDeadConnectConfig as Lt, signInSecretOf as M, describeToken as Mt, checkRunnerArgv as N, formatPath as Nt, takeCompoundMember as O, outputSitesOf as Ot, isRunnerArgsSchema as P, isPlainObject as Pt, CONNECT_RUNNER as Q, computeOutputsHash as R, resolveHostPlugins as Rt, resolveUserDataPlaceholders as S, substituteBuiltinEnv as St, SpawnHostError as T, checkTokenSites as Tt, lintOutputsFile as U, hostFileLabel as Ut, lintHostImportGraph as V, findHostPackage as Vt, loadHost as W, locateHost as Wt, stripComments as X, scanHostImports as Y, withoutHostsMessage as Z, processResolveEnv as _, PlanError as _t, memberProcessOf as a, kindShapeIssues as at, runnerOutputsSchema as b, BUILTIN_ENV_NAMES as bt, prepareMember as c, packageBuildRefusal as ct, takesCspRegistrySync as d, validateHost as dt, RunnerError as et, runnerHandleSchema as f, TokenResolutionError as ft, loadProducers as g, unsetEnvMessage as gt, OUTPUT_DATA_DIRS_ENV as h, resolveHostOutputs as ht, memberCycle as i, isSchemaLike as it, signInMembersOf as j, collectTokenSites as jt, announceSignInLinks as k, refKey as kt, runCompound as l, resolveRunnerModule as lt, compoundOutputSource as m, emptyMaps as mt, compoundStartVerb as n, getVerb as nt, memberVerbOf as o, knownVerbIssues as ot, toStartedHandle as p, describeMapElements as pt, probeHostsFolder as q, CONNECT_PLUGIN_OWNED_SLICES as qt, holdStopRequests as r, hostSchemaIssues as rt, planForeground as s, listVerbs as st, STOP_STREAM_LIMIT_MS as t, STORE_VERBS as tt, stopStreamOf as u, validateDeclaredHost as ut, producerOutputsSchemas as v, memberForRef as vt, SPAWN_STOPPING_NOTE as w, checkOutputPaths as wt, defaultUserDataDir as x, isBuiltinEnvName as xt, runRecordOutputSource as y, planCompound as yt, describeHostOutputs as z, resolvePluginContributions as zt };
4721
3646
 
4722
- //# sourceMappingURL=compound-Q9sZSEZF.mjs.map
3647
+ //# sourceMappingURL=compound-g6x_KkWp.mjs.map