@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.
- package/dist/{compound-L62ALvYc.d.mts → compound-BLhEewO6.d.mts} +8 -2
- package/dist/compound-BLhEewO6.d.mts.map +1 -0
- package/dist/{compound-Q9sZSEZF.mjs → compound-g6x_KkWp.mjs} +133 -1208
- package/dist/compound-g6x_KkWp.mjs.map +1 -0
- package/dist/control-channel-DVn4dvfQ.d.mts +206 -0
- package/dist/control-channel-DVn4dvfQ.d.mts.map +1 -0
- package/dist/control-channel.d.mts +2 -2
- package/dist/control-channel.mjs +358 -47
- package/dist/control-channel.mjs.map +1 -1
- package/dist/host-entry-B8n_590_.mjs +188 -0
- package/dist/host-entry-B8n_590_.mjs.map +1 -0
- package/dist/index.d.mts +68 -102
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +6 -3
- package/dist/index.mjs.map +1 -1
- package/dist/instance-C6uugZ32.d.mts +165 -0
- package/dist/instance-C6uugZ32.d.mts.map +1 -0
- package/dist/instance.d.mts +3 -0
- package/dist/instance.mjs +145 -0
- package/dist/instance.mjs.map +1 -0
- package/dist/kill-tree.d.mts +2 -0
- package/dist/kill-tree.d.mts.map +1 -1
- package/dist/kill-tree.mjs +1 -1
- package/dist/kill-tree.mjs.map +1 -1
- package/dist/run-record-C6oTZF_C.mjs +1077 -0
- package/dist/run-record-C6oTZF_C.mjs.map +1 -0
- package/dist/runners/compound.d.mts +1 -1
- package/dist/runners/compound.mjs +2 -1
- package/dist/runners/compound.mjs.map +1 -1
- package/dist/spawn-host-DWroRe1S.d.mts +107 -0
- package/dist/spawn-host-DWroRe1S.d.mts.map +1 -0
- package/dist/supervisor-record.d.mts +88 -0
- package/dist/supervisor-record.d.mts.map +1 -0
- package/dist/supervisor-record.mjs +127 -0
- package/dist/supervisor-record.mjs.map +1 -0
- package/dist/supervisor.d.mts +205 -0
- package/dist/supervisor.d.mts.map +1 -0
- package/dist/supervisor.mjs +905 -0
- package/dist/supervisor.mjs.map +1 -0
- package/package.json +21 -3
- package/dist/compound-L62ALvYc.d.mts.map +0 -1
- package/dist/compound-Q9sZSEZF.mjs.map +0 -1
- package/dist/control-channel-eqvyUF03.d.mts +0 -123
- package/dist/control-channel-eqvyUF03.d.mts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-record-C6oTZF_C.mjs","names":[],"sources":["../src/drive-schema.ts","../src/plugins.ts","../src/host-schemas.ts","../src/instance-key.ts","../src/run-record-schema.ts","../src/run-record.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { tokenable, type TokenableSchema } from \"./tokens.js\";\n\n/**\n * The schema half of drives.ts, zod only so `./schema` stays neutral.\n * - slug: the SEEDING KEY (idempotence); id optional (stable identity).\n * - preferredEditor: stored at header.meta.preferredEditor; Connect config's\n * `app` is the legacy alias.\n * - remote.url: a drive served elsewhere; local fields are ignored for it.\n * Token-able (`$output` on a producer's `drives.<slug>.url`).\n */\nexport function buildDriveDeclarationSchema(\n urlField: (schema: z.ZodString) => TokenableSchema<z.ZodString>,\n) {\n return z.strictObject({\n slug: z.string().min(1),\n id: z.string().min(1).optional(),\n /** Derive the id from the project path (`<slug>-<hash of the path>`) — the\n * same ids classic `ph vetra` produced. `true` serves the drive under the\n * hashed slug too (the vetra drive's slug IS its hashed id); `\"id\"` hashes\n * only the id and keeps the declared slug (the classic Workflows drive:\n * `/d/workflows`, id `workflows-<hash>`). */\n projectHash: z.union([z.boolean(), z.literal(\"id\")]).optional(),\n /** What a missing drive is created as. Default powerhouse/document-drive. */\n documentType: z\n .enum([\"powerhouse/document-drive\", \"powerhouse/reactor-drive\"])\n .optional(),\n name: z.string().min(1).optional(),\n icon: z.string().optional(),\n preferredEditor: z.string().optional(),\n sharingType: z.enum([\"public\", \"private\", \"shared\"]).optional(),\n availableOffline: z.boolean().optional(),\n remote: z.strictObject({ url: urlField(z.string().min(1)) }).optional(),\n });\n}\n\nexport const driveDeclarationSchema = buildDriveDeclarationSchema(tokenable);\n\nexport type DriveDeclaration = z.infer<typeof driveDeclarationSchema>;\n\nexport const drivesSchema = z.array(driveDeclarationSchema);\n\n/** The project-hashed drive id (`${slug}-${sha256(projectRoot)[0..8]}`) with\n * the hash function injected, so neutral consumers (a browser monitor) can\n * pass `crypto.subtle`-derived or precomputed hex. drives.ts binds it to\n * node:crypto as `projectDriveId`. */\nexport function projectDriveIdWith(\n sha256Hex: (input: string) => string,\n projectRoot: string,\n slug: string,\n): string {\n return `${slug}-${sha256Hex(projectRoot).substring(0, 8)}`;\n}\n","import { z } from \"zod\";\n\n/**\n * R1 — the host plugin framework (bridge-runners-to-plugins plan,\n * customization-references/host-core as the blueprint).\n *\n * A plugin is hooks + contributions; hooks are boot wiring (main realm only),\n * contributions are declarative, serializable surface. Host RUNTIMES define\n * the hook vocabulary and interleave their own wiring between stages — they\n * are never plugins themselves.\n *\n * host.js carries the COMPOSITION as `runner.plugins` entries:\n * string | { module, enabled?, verbs?, config? }\n * Presence is activation (enabled defaults true); `verbs` scopes an entry to\n * matching run verbs; `config` is validated against the plugin's declared\n * zod schema. Entries resolve from the PROJECT's dependency tree exactly\n * like runner modules.\n */\n\nexport class PluginError extends Error {\n constructor(message: string, hint?: string) {\n super(hint ? `${message}\\n Hint: ${hint}` : message);\n this.name = \"PluginError\";\n }\n}\n\n/* ------------------------------------------------------------------ entries */\n\nexport const pluginEntryObjectSchema = z.strictObject({\n module: z.string().min(1),\n /** Presence is activation BY DEFAULT; false is the explicit off-switch. */\n enabled: z.boolean().optional(),\n /** \"*\" (default) or the run verbs this entry is active for. */\n verbs: z\n .union([z.literal(\"*\"), z.array(z.string().min(1)).min(1)])\n .optional(),\n /** Validated against the plugin's declared configSchema at resolution. */\n config: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const pluginEntrySchema = z.union([\n z.string().min(1),\n pluginEntryObjectSchema,\n]);\n\n/** The validated (runtime) entry shape. Authors write `PluginEntry`\n * (host-types.ts), which types known plugins' configs. */\nexport type PluginEntryData = z.infer<typeof pluginEntrySchema>;\nexport type { PluginEntry } from \"./host-types.js\";\n\nexport interface NormalizedPluginEntry {\n module: string;\n enabled: boolean;\n verbs: \"*\" | string[];\n config: Record<string, unknown>;\n}\n\nexport function normalizePluginEntry(\n entry: PluginEntryData,\n): NormalizedPluginEntry {\n if (typeof entry === \"string\") {\n return { module: entry, enabled: true, verbs: \"*\", config: {} };\n }\n return {\n module: entry.module,\n enabled: entry.enabled ?? true,\n verbs: entry.verbs ?? \"*\",\n config: entry.config ?? {},\n };\n}\n\n/** Module is the identity key: a duplicate makes override targeting and\n * ordering ambiguous, so it fails loudly. */\nexport function normalizePluginEntries(\n entries: readonly PluginEntryData[],\n where: string,\n): NormalizedPluginEntry[] {\n const normalized = entries.map(normalizePluginEntry);\n const seen = new Set<string>();\n for (const entry of normalized) {\n if (seen.has(entry.module)) {\n throw new PluginError(\n `${where}: plugin \"${entry.module}\" is listed twice.`,\n \"Module specifiers are the identity key of a composition; a plugin meant to run twice needs distinct subpath specifiers.\",\n );\n }\n seen.add(entry.module);\n }\n return normalized;\n}\n\nexport function entryActiveForVerb(\n entry: NormalizedPluginEntry,\n verb: string,\n): boolean {\n if (!entry.enabled) return false;\n return entry.verbs === \"*\" || entry.verbs.includes(verb);\n}\n\n/* ---------------------------------------------------------------- hierarchy */\n\n/**\n * The appliesTo hierarchy. \"reactor\" is the base every reactor host extends;\n * \"compound\" is its own branch (plugins over the member set — e.g. the clint\n * proxy). Host runtimes register their id with a parent; compatibility walks\n * the parent chain.\n */\nconst HOST_TYPE_PARENTS: Record<string, string | null> = {\n reactor: null,\n compound: null,\n connect: \"reactor\",\n switchboard: \"reactor\",\n mastra: \"reactor\",\n};\n\nexport function registerHostType(id: string, parent: string | null): void {\n if (id in HOST_TYPE_PARENTS && HOST_TYPE_PARENTS[id] !== parent) {\n throw new PluginError(\n `Host type \"${id}\" is already registered with parent \"${String(HOST_TYPE_PARENTS[id])}\".`,\n );\n }\n HOST_TYPE_PARENTS[id] = parent;\n}\n\nexport function hostTypeSatisfies(\n hostType: string,\n appliesTo: string,\n): boolean {\n let current: string | null = hostType;\n while (current !== null) {\n if (current === appliesTo) return true;\n current = current in HOST_TYPE_PARENTS ? HOST_TYPE_PARENTS[current] : null;\n }\n return false;\n}\n\n/* ------------------------------------------------------------------- plugin */\n\n/** Hook kinds (v1 §2.2). The hook VOCABULARY is defined by host runtimes;\n * plugins implement subsets of it. */\nexport type Provide<T, C> = (ctx: C) => T | Promise<T>;\nexport type Transform<T, C> = (value: T, ctx: C) => T | Promise<T>;\nexport type Observe<C> = (ctx: C) => void | Promise<void>;\n\n/**\n * Core contributions — declarative, serializable, realm-crossing. Host\n * runtimes extend this with their own kinds (UI slots live in connect-host,\n * never here). `drives` entries use the drive declaration shape from\n * drives.ts; kept as unknown here to avoid a cycle — the merge is shape-blind.\n */\nexport interface Contributions {\n drives?: unknown[];\n packages?: string[];\n configDeclarations?: { name: string; type?: string; description?: string }[];\n [kind: string]: unknown[] | undefined;\n}\n\nexport interface HostPlugin<\n THooks = Record<string, unknown>,\n TConfig = unknown,\n> {\n /** Stable id; used in ordering, dependsOn, and every diagnostic. */\n name: string;\n /** Host-type requirement; the entry is rejected on a host outside the\n * hierarchy branch. Default: \"reactor\". */\n appliesTo?: string;\n /** Coarse ordering bucket (Vite-style). Default: \"normal\". */\n enforce?: \"pre\" | \"post\";\n /** Hard dependencies on OTHER PLUGINS — the host runtime is implied and\n * never named. Missing dependency or cycle fails boot naming both sides. */\n dependsOn?: string[];\n /** Declared config shape; entry config is validated against it. A plugin\n * without a schema accepts no config (passing one is a boot error). */\n configSchema?: z.ZodType<TConfig>;\n hooks?: Partial<THooks>;\n contributions?: Contributions;\n}\n\n/** A plugin module default-exports either a HostPlugin object (no config\n * accepted) or a factory `(config) => HostPlugin`. */\nexport type HostPluginModule<\n THooks = Record<string, unknown>,\n TConfig = unknown,\n> =\n | HostPlugin<THooks, TConfig>\n | ((config: TConfig) => HostPlugin<THooks, TConfig>);\n\nexport interface ResolvedPlugin<THooks = Record<string, unknown>> {\n entry: NormalizedPluginEntry;\n plugin: HostPlugin<THooks>;\n /** Provenance for contribution merge ordering. */\n provenance: \"built-in\" | \"local\" | \"dependency\";\n}\n\n/* ----------------------------------------------------------------- ordering */\n\n/** Registration order, bucketed pre → normal → post (stable within buckets),\n * then dependsOn topo-sorted within the bucketed order. */\nexport function resolveOrder<THooks>(\n plugins: readonly HostPlugin<THooks>[],\n): HostPlugin<THooks>[] {\n const buckets: Record<\"pre\" | \"normal\" | \"post\", HostPlugin<THooks>[]> = {\n pre: [],\n normal: [],\n post: [],\n };\n for (const plugin of plugins)\n buckets[plugin.enforce ?? \"normal\"].push(plugin);\n const bucketed = [...buckets.pre, ...buckets.normal, ...buckets.post];\n\n const byName = new Map(bucketed.map((p) => [p.name, p]));\n for (const plugin of bucketed) {\n for (const dep of plugin.dependsOn ?? []) {\n if (!byName.has(dep)) {\n throw new PluginError(\n `Plugin \"${plugin.name}\" depends on missing plugin \"${dep}\".`,\n \"dependsOn names PLUGINS only — the host runtime is implied and never named.\",\n );\n }\n }\n }\n\n const ordered: HostPlugin<THooks>[] = [];\n const state = new Map<string, \"visiting\" | \"done\">();\n const visit = (plugin: HostPlugin<THooks>, chain: string[]): void => {\n const mark = state.get(plugin.name);\n if (mark === \"done\") return;\n if (mark === \"visiting\") {\n throw new PluginError(\n `Plugin dependency cycle: ${[...chain, plugin.name].join(\" -> \")}.`,\n );\n }\n state.set(plugin.name, \"visiting\");\n for (const dep of plugin.dependsOn ?? []) {\n visit(byName.get(dep)!, [...chain, plugin.name]);\n }\n state.set(plugin.name, \"done\");\n ordered.push(plugin);\n };\n for (const plugin of bucketed) visit(plugin, []);\n return ordered;\n}\n\n/* -------------------------------------------------------------------- hooks */\n\nexport async function runProvideHook<T, C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n): Promise<T | undefined> {\n const impls = plugins.filter((p) => typeof p.hooks?.[name] === \"function\");\n if (impls.length > 1) {\n throw new PluginError(\n `Hook \"${name}\" is provided by ${impls.map((p) => `\"${p.name}\"`).join(\" and \")} — provide hooks have one winner.`,\n );\n }\n const impl = impls[0]?.hooks?.[name] as Provide<T, C> | undefined;\n return impl ? await impl(ctx) : undefined;\n}\n\nexport async function runTransformHook<T, C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n seed: T,\n): Promise<T> {\n let value = seed;\n for (const plugin of plugins) {\n const impl = plugin.hooks?.[name] as Transform<T, C> | undefined;\n if (typeof impl === \"function\") value = await impl(value, ctx);\n }\n return value;\n}\n\n/** Sequential observe, in plugin order — for lifecycle moments whose order\n * is load-bearing (teardown: the switchboard stops privacy before workflows\n * before the api, per the carve map). */\nexport async function runObserveHookSequential<C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n): Promise<void> {\n for (const plugin of plugins) {\n const impl = plugin.hooks?.[name] as Observe<C> | undefined;\n if (typeof impl === \"function\") await impl(ctx);\n }\n}\n\nexport async function runObserveHook<C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n): Promise<void> {\n await Promise.all(\n plugins.map(async (plugin) => {\n const impl = plugin.hooks?.[name] as Observe<C> | undefined;\n if (typeof impl === \"function\") await impl(ctx);\n }),\n );\n}\n\n/* ------------------------------------------------------------ contributions */\n\nexport interface ContributionSource {\n pluginName: string;\n provenance: \"built-in\" | \"local\" | \"dependency\";\n}\n\nexport interface MergedContribution<T = unknown> {\n value: T;\n source: ContributionSource;\n}\n\n/** Array kinds concatenate in provenance-then-order sequence (built-in first,\n * so later sources read as overrides where consumers want last-wins). */\nexport function mergeContributions(\n resolved: readonly {\n plugin: HostPlugin;\n provenance: ContributionSource[\"provenance\"];\n }[],\n): Record<string, MergedContribution[]> {\n const rank: Record<ContributionSource[\"provenance\"], number> = {\n \"built-in\": 0,\n local: 1,\n dependency: 2,\n };\n const sorted = [...resolved].sort(\n (a, b) => rank[a.provenance] - rank[b.provenance],\n );\n const merged: Record<string, MergedContribution[]> = {};\n for (const { plugin, provenance } of sorted) {\n for (const [kind, values] of Object.entries(plugin.contributions ?? {})) {\n if (!values) continue;\n const bucket = (merged[kind] ??= []);\n for (const value of values) {\n bucket.push({ value, source: { pluginName: plugin.name, provenance } });\n }\n }\n }\n return merged;\n}\n\n// The default Connect composition is worked out in the browser too.\nexport {\n CONNECT_PLUGIN_OWNED_SLICES,\n defaultConnectComposition,\n type ConnectPluginSlices,\n type OwnedConfigSlice,\n} from \"./connect-composition.js\";\n","import { switchboardOfDrive } from \"@powerhousedao/shared/host-tokens\";\nimport { isOriginPlaceholderUrl } from \"@powerhousedao/shared/connect/origin-placeholder\";\nimport { z } from \"zod\";\nimport { buildDriveDeclarationSchema } from \"./drive-schema.js\";\nimport { pluginEntrySchema } from \"./plugins.js\";\nimport {\n envTokenable,\n tokenable,\n type EnvToken,\n type TokenableSchema,\n type TokenMode,\n} from \"./tokens.js\";\n\n/**\n * The zod single source for host.js blocks (typed-host-configs G1). Every\n * host type is z.input/z.output of these schemas; nothing is hand-mirrored.\n * Top-level host objects and the `reactor` block are STRICT (a typo fails);\n * `runner` stays loose until each runner declares its options (T2), and\n * `config` is runner-defined.\n *\n * Token-able fields (typed-host-configs 3.5): `reactor.backends.*.remote.url`\n * (required, a switchboard drive address), `reactor.drives` (whole list, e.g. `$map`),\n * `reactor.drives[].remote.url` and `storage.dataDir` (`$env` only). Their z.input admits tokens, their z.output is the resolved type.\n */\n\n/** A host's `name` keys its run record, `.ph/run/<name>.json`, so it must be\n * one safe path segment. */\nexport const HOST_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\nexport const HOST_NAME_MAX_LENGTH = 128;\nexport const HOST_NAME_MESSAGE =\n \"A host name is used as a file name, so use only letters, digits, '.', '_' and '-', start with a letter or digit, and keep it to 128 characters.\";\nexport const hostNameSchema = z\n .string()\n .min(1)\n .max(HOST_NAME_MAX_LENGTH, HOST_NAME_MESSAGE)\n .regex(HOST_NAME_PATTERN, HOST_NAME_MESSAGE);\n\n/** An npm package name, as `<package>/<host>` names a package that supplies\n * hosts: `name` or `@scope/name`, each part letters, digits, '-', '.', '_'\n * and '~', not starting with '.' or '_'. Each part is one folder name, the\n * one the package has under node_modules. */\nexport const PACKAGE_NAME_PATTERN =\n /^(?:@[A-Za-z0-9~-][A-Za-z0-9._~-]*\\/)?[A-Za-z0-9~-][A-Za-z0-9._~-]*$/;\n\n/** How a compound names a member's host: its folder under the project's\n * `hosts/` (or, in a package's compound, the package's first), or\n * `<package>/<host>` for one an installed package supplies. */\nexport const HOST_REF_PATTERN = new RegExp(\n `^(?:${PACKAGE_NAME_PATTERN.source.slice(1, -1)}/)?${HOST_NAME_PATTERN.source.slice(1, -1)}$`,\n);\nexport const HOST_REF_MESSAGE =\n \"A member's host is a host folder (`switchboard`), or `<package>/<host>` (`@acme/tools/studio`) for one an installed package supplies.\";\n\n/**\n * A URL, or one written against the page origin (`${origin}/graphql`): the\n * browser resolves the placeholder when it loads Connect's config, for a\n * member whose own server proxies the switchboard's paths.\n */\nexport const originOrUrlSchema = z.union([\n z.url(),\n z.string().refine(isOriginPlaceholderUrl, {\n message: \"a URL, or ${origin}/<path> for a proxied sibling\",\n }),\n]);\n\nexport const profileSchema = z.strictObject({\n appId: z.string().min(1).optional(),\n name: z.string().min(1).optional(),\n description: z.string().optional(),\n icon: z.string().optional(),\n});\n\nexport const reactorProtocolSchema = z.strictObject({\n featureFlags: z\n .strictObject({\n documentDecisions: z.boolean().optional(),\n authEnforcement: z.boolean().optional(),\n authGroups: z.boolean().optional(),\n authConditions: z.boolean().optional(),\n undoV3: z.boolean().optional(),\n })\n .optional(),\n createSignaturePolicy: z.enum([\"legacy\", \"v2-required\"]).optional(),\n unsupportedStoredDocuments: z.enum([\"refuse\", \"read-only\"]).optional(),\n});\n\nexport const runnerKindSchema = z.enum([\"reactor\", \"compound\"]);\nexport type RunnerKind = z.infer<typeof runnerKindSchema>;\n\n/** A compound member's process: its own, or the compound's (`shared`). */\nexport const memberProcessSchema = z.enum([\"own\", \"shared\"]);\nexport type MemberProcess = z.infer<typeof memberProcessSchema>;\n\nexport const reactorBackendKindSchema = z.enum([\n \"in-process\",\n \"worker\",\n \"remote\",\n]);\n\n// Path-equality for the one-dir guard: pure string normalisation (the host\n// core stays Node-free); the server repeats the check with path.resolve.\nconst samePath = (a: string, b: string): boolean => {\n const norm = (p: string) =>\n p.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\").replace(/^\\.\\//, \"\");\n return norm(a) === norm(b);\n};\n\n/** Compound wiring: the generic compound runner's `config` block.\n * (`projectDrivesIntoConnect` and `drivesPublicBase` were removed in T3: a\n * member consumes another member's drives through `$output` tokens.) */\nexport const compoundWiringSchema = z.strictObject({\n /** Member start order; must name declared children and agree with the\n * output-token dependencies (resolve/plan.ts). Optional: without it the\n * order is derived from the tokens. Unnamed members start after the named\n * ones, in declaration order. */\n startOrder: z.array(z.string().min(1)).optional(),\n /** Write .ph/run/<host>.json (default true). */\n runtimeRecord: z.boolean().optional(),\n /** Patch the baked CSP for the runtime registry on a served Connect\n * member (forwarded as `runner.cspRegistrySync` to every member whose\n * runner is `@powerhousedao/ph-cli/runners/connect`). */\n cspRegistrySync: z.boolean().optional(),\n});\n\n/** `config.startOrder ⊆ keys(children)`, checked where both are visible.\n * Apply it LAST (`.superRefine(refineStartOrder)`) to a runner's final host\n * schema: zod refuses to `.extend()` a refined object. */\nexport function refineStartOrder(\n host: { children: Record<string, unknown>; config?: Record<string, unknown> },\n ctx: z.RefinementCtx,\n): void {\n const startOrder = host.config?.startOrder;\n if (!Array.isArray(startOrder)) return;\n const members = Object.keys(host.children);\n startOrder.forEach((name: unknown, index) => {\n if (startOrder.indexOf(name) !== index) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"config\", \"startOrder\", index],\n message: `startOrder names \"${String(name)}\" twice; each member starts once.`,\n });\n return;\n }\n if (typeof name === \"string\" && members.includes(name)) return;\n ctx.addIssue({\n code: \"custom\",\n path: [\"config\", \"startOrder\", index],\n message: `startOrder names \"${String(name)}\", which is not a member. Members: ${members.join(\", \") || \"(none)\"}.`,\n });\n });\n}\n\n/** How a schema set wraps its token-able fields. Both modes share one static\n * type (declared input, resolved output); they differ at runtime only. */\ninterface FieldWrappers {\n any: <S extends z.ZodType>(schema: S) => TokenableSchema<S>;\n env: <S extends z.ZodType>(schema: S) => TokenableSchema<S, EnvToken>;\n}\n\nconst ALLOW_TOKENS: FieldWrappers = { any: tokenable, env: envTokenable };\n// A one-option union: the same validation as `schema`, typed like the\n// \"allow\" wrappers so both modes share HostSchemas.\nconst FORBID_TOKENS: FieldWrappers = {\n any: (schema) => z.union([schema]),\n env: (schema) => z.union([schema]),\n};\n\n/** The replacement a non-drive `remote.url` message names. */\nfunction useDriveUrl(host = \"switchboard\", member?: string): string {\n const memberPart = member ? `, member: \"${member}\"` : \"\";\n return (\n `remote: { url: ${host}.drives.<slug>.url } with ${host} from ../${host}/outputs.js, ` +\n `or remote: { url: { $output: { host: \"${host}\"${memberPart}, path: [\"drives\", \"<slug>\", \"url\"] } } }`\n );\n}\n\n/** The `$output` of a declared `remote.url` that reads `endpoints.graphql`. */\nfunction endpointsGraphqlRef(\n url: unknown,\n): { host: string; member?: string } | undefined {\n if (typeof url !== \"object\" || url === null || !(\"$output\" in url)) {\n return undefined;\n }\n const ref = (url as { $output: unknown }).$output;\n if (typeof ref !== \"object\" || ref === null) return undefined;\n const { host, member, path } = ref as Record<string, unknown>;\n if (typeof host !== \"string\" || !Array.isArray(path)) return undefined;\n if (path.join(\".\") !== \"endpoints.graphql\") return undefined;\n return { host, ...(typeof member === \"string\" ? { member } : {}) };\n}\n\n/** The slug a drive link names: a `drives.<slug>.url` token's slug or a\n * literal address's served slug; undefined when only runtime knows it. */\nfunction linkedSlug(url: unknown): string | undefined {\n if (typeof url === \"string\") return switchboardOfDrive(url)?.slug;\n const ref =\n typeof url === \"object\" && url !== null && \"$output\" in url\n ? (url as { $output: { path?: unknown } }).$output\n : undefined;\n const path = Array.isArray(ref?.path) ? (ref.path as unknown[]) : [];\n return path.length === 3 &&\n path[0] === \"drives\" &&\n typeof path[1] === \"string\" &&\n path[2] === \"url\"\n ? path[1]\n : undefined;\n}\n\ninterface DeclaredReactorHost {\n runner?: { plugins?: unknown };\n config?: unknown;\n reactor?: {\n backends?: Record<string, { kind: string; remote?: { url: unknown } }>;\n placement?: {\n primary?: string;\n drives?: Record<string, string>;\n newDrives?: string;\n };\n drives?: unknown;\n };\n}\n\n/** The drives a declared host names (home drives, `reactor.drives`, plugin\n * `config.drive` links), or undefined when one is known only at runtime. */\nfunction knownDriveSlugs(host: DeclaredReactorHost): string[] | undefined {\n const reactor = host.reactor ?? {};\n const slugs: string[] = [];\n for (const backend of Object.values(reactor.backends ?? {})) {\n if (backend.kind !== \"remote\") continue;\n const slug = linkedSlug(backend.remote?.url);\n if (slug === undefined) return undefined;\n slugs.push(slug);\n }\n if (reactor.drives !== undefined) {\n if (!Array.isArray(reactor.drives)) return undefined;\n for (const drive of reactor.drives as { slug?: unknown }[]) {\n if (typeof drive.slug === \"string\") slugs.push(drive.slug);\n }\n }\n const plugins = Array.isArray(host.runner?.plugins)\n ? (host.runner.plugins as unknown[])\n : [];\n for (const entry of plugins) {\n const config =\n typeof entry === \"object\" && entry !== null && \"config\" in entry\n ? (entry as { config: unknown }).config\n : undefined;\n if (typeof config !== \"object\" || config === null) continue;\n if (!(\"drive\" in config) || config.drive === undefined) continue;\n const slug = linkedSlug(config.drive);\n if (slug === undefined) return undefined;\n slugs.push(slug);\n }\n for (const drive of connectDefaultDrives(host.config)) {\n if (typeof drive !== \"object\" || drive === null || !(\"url\" in drive)) {\n continue;\n }\n const slug = linkedSlug(drive.url);\n if (slug === undefined) return undefined;\n slugs.push(slug);\n }\n return slugs;\n}\n\n/** A Connect host's `config.drives.defaultDrives`, unchecked. */\nfunction connectDefaultDrives(config: unknown): unknown[] {\n const drives =\n typeof config === \"object\" && config !== null && \"drives\" in config\n ? (config as { drives: unknown }).drives\n : undefined;\n const list =\n typeof drives === \"object\" && drives !== null && \"defaultDrives\" in drives\n ? (drives as { defaultDrives: unknown }).defaultDrives\n : undefined;\n return Array.isArray(list) ? list : [];\n}\n\n/** Declared form, at host level so plugin drives are seen: a placement key\n * must name a drive the host names, when every drive is knowable. A host\n * with no remote backend is not checked: its plugins may contribute drives\n * (a switchboard's workflows drive) that no field names. */\nfunction refineDeclaredPlacementKeys(\n host: DeclaredReactorHost,\n ctx: z.RefinementCtx,\n): void {\n const placed = Object.keys(host.reactor?.placement?.drives ?? {});\n if (placed.length === 0) return;\n const remote = Object.values(host.reactor?.backends ?? {}).some(\n (b) => b.kind === \"remote\",\n );\n if (!remote) return;\n const known = knownDriveSlugs(host);\n if (!known) return;\n // A literal address may carry the hashed slug of a `projectHash` drive.\n const names = (slug: string, served: string) =>\n served === slug ||\n (served.startsWith(`${slug}-`) &&\n /^[0-9a-f]{8}$/.test(served.slice(slug.length + 1)));\n for (const slug of placed) {\n if (known.some((served) => names(slug, served))) continue;\n ctx.addIssue({\n code: \"custom\",\n path: [\"reactor\", \"placement\", \"drives\", slug],\n message: `placement.drives.${slug} names no drive this host links to or declares (${[...new Set(known)].join(\", \") || \"none\"}).`,\n });\n }\n}\n\ninterface ResolvedReactorBlock {\n backends?: Record<string, { kind: string; remote?: { url: unknown } }>;\n placement?: { drives?: Record<string, string> };\n drives?: unknown;\n}\n\n/** Resolved-form checks across backends, drives and placement: one base is\n * one remote backend, and a drive placed on a remote is on its switchboard. */\nfunction refineResolvedReactor(\n reactor: ResolvedReactorBlock,\n ctx: z.RefinementCtx,\n): void {\n const backends = reactor.backends ?? {};\n const baseOf = new Map<string, string>();\n const byBase = new Map<string, string>();\n // Every switchboard a slug is linked on: one slug on two is ambiguous.\n const linked = new Map<string, Set<string>>();\n const link = (slug: string, base: string) =>\n linked.set(slug, (linked.get(slug) ?? new Set()).add(base));\n for (const [name, backend] of Object.entries(backends)) {\n const url = backend.remote?.url;\n if (backend.kind !== \"remote\" || typeof url !== \"string\") continue;\n const home = switchboardOfDrive(url);\n if (!home) continue;\n baseOf.set(name, home.base);\n link(home.slug, home.base);\n const first = byBase.get(home.base);\n if (first === undefined) {\n byBase.set(home.base, name);\n continue;\n }\n ctx.addIssue({\n code: \"custom\",\n path: [\"backends\", name, \"remote\", \"url\"],\n message: `backends \"${first}\" and \"${name}\" both open drives on the same switchboard (${home.base}). Keep \"${first}\", and list the second drive under reactor.drives with its remote.url instead.`,\n });\n }\n\n const kept = new Set<string>();\n const declared = Array.isArray(reactor.drives)\n ? (reactor.drives as { slug: string; remote?: { url: string } }[])\n : [];\n declared.forEach((drive, index) => {\n if (!drive.remote) {\n kept.add(drive.slug);\n return;\n }\n const at = switchboardOfDrive(drive.remote.url);\n // An empty url already fails the field's own check.\n if (at || drive.remote.url === \"\") {\n if (at) link(drive.slug, at.base);\n return;\n }\n ctx.addIssue({\n code: \"custom\",\n path: [\"drives\", index, \"remote\", \"url\"],\n message: `remote.url must be a switchboard drive address (<switchboard>/d/<slug>), not ${drive.remote.url}: sync needs the drive. Use url: switchboard.drives.<slug>.url, or url: { $output: { host: \"switchboard\", path: [\"drives\", \"<slug>\", \"url\"] } }.`,\n });\n });\n\n const nameOf = (base: string) => byBase.get(base) ?? base;\n for (const [slug, name] of Object.entries(reactor.placement?.drives ?? {})) {\n const at = [\"placement\", \"drives\", slug];\n const on = [...(linked.get(slug) ?? [])];\n // Two drives answer to the key, whichever backend it names.\n if (on.length > 0 && kept.has(slug)) {\n ctx.addIssue({\n code: \"custom\",\n path: at,\n message: `Drive \"${slug}\" is both this reactor's own drive and on ${on.map(nameOf).join(\" and \")}. Rename one, or link only one.`,\n });\n continue;\n }\n if (on.length > 1) {\n ctx.addIssue({\n code: \"custom\",\n path: at,\n message: `Drive \"${slug}\" is on both ${on.map(nameOf).join(\" and \")}. Rename one, or link only one.`,\n });\n continue;\n }\n const base = baseOf.get(name);\n if (base === undefined) continue;\n if (on.length === 0) {\n // A key that names no drive here (a hashed home drive) is not checked.\n if (!kept.has(slug)) continue;\n ctx.addIssue({\n code: \"custom\",\n path: at,\n message: `placement.drives.${slug} opens drive \"${slug}\" on \"${name}\", but this reactor keeps that drive itself. Only a drive on a switchboard can open there without a copy.`,\n });\n continue;\n }\n if (on[0] === base) continue;\n ctx.addIssue({\n code: \"custom\",\n path: at,\n message: `placement.drives.${slug} opens drive \"${slug}\" on \"${name}\" (${base}), but the drive is on ${on[0]}. Place it on the backend for that switchboard.`,\n });\n }\n}\n\n/** `remote` keys that tune a connection, so only a remote backend has them. */\nconst REMOTE_ONLY_KEYS = [\"requestTimeoutMs\", \"breaker\", \"realtime\"] as const;\n\n/**\n * Builds the host schema set. \"allow\" (declared form) accepts `T | Token` in\n * every token-able field; \"forbid\" (resolved form) accepts `T` only.\n */\nfunction buildHostSchemas(tokenField: FieldWrappers) {\n const resolved = tokenField === FORBID_TOKENS;\n const reactorBackendSchema = z\n .strictObject({\n kind: reactorBackendKindSchema,\n storage: z\n .strictObject({\n kind: z.enum([\"idb\", \"memory\", \"path\", \"postgres\"]),\n /** `\"${userData}/…\"` sugar or `{ $env: \"NAME\" }`. */\n dataDir: tokenField.env(z.string()).optional(),\n url: z.string().optional(),\n })\n .optional(),\n readModel: z.strictObject({ url: z.string().optional() }).optional(),\n packages: z\n .strictObject({\n cdnUrl: z.string().optional(),\n specs: z.array(z.string()).optional(),\n /** on-demand model resolution (was DYNAMIC_MODEL_LOADING). */\n dynamic: z.boolean().optional(),\n })\n .optional(),\n // A switchboard drive address, `<base>/d/<slug>`: typically a\n // producer's `drives.<slug>.url` output token. The backend is the\n // switchboard at `<base>`. `${origin}/d/<slug>` when the member's own\n // server proxies the switchboard (the browser then calls its page\n // origin; see `runner.proxy` on the connect runner).\n remote: z\n .strictObject({\n url: tokenField.any(originOrUrlSchema),\n /** Give up on one request to this switchboard after this long. Default 30_000. */\n requestTimeoutMs: z.number().int().positive().optional(),\n /** After `failures` failed requests in a row, send nothing for\n * `openMs`. Default { failures: 3, openMs: 30_000 }. `false`:\n * never stop trying. */\n breaker: z\n .union([\n z.literal(false),\n z.strictObject({\n failures: z.number().int().min(1).optional(),\n openMs: z.number().int().nonnegative().optional(),\n }),\n ])\n .optional(),\n /** Live updates over a socket (the router's GraphQL\n * subscriptions, not drive sync). Default true. */\n realtime: z.boolean().optional(),\n })\n .optional(),\n })\n // Two PGlite instances on one data dir corrupt it: the reactor store\n // (storage.dataDir) and the read-model store (readModel.url) must differ.\n // Postgres is exempt: one database legitimately serves both stores.\n .superRefine((backend, ctx) => {\n // 2.1 \"a remote backend needs url\": `remote` is optional for the\n // in-process/worker kinds, but a remote backend attaches by URL only.\n if (backend.kind === \"remote\" && !backend.remote) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"remote\", \"url\"],\n message: `a \"remote\" backend needs remote.url, a switchboard drive address: ${useDriveUrl()}.`,\n });\n }\n if (backend.kind !== \"remote\" && backend.remote) {\n for (const key of REMOTE_ONLY_KEYS) {\n if (backend.remote[key] === undefined) continue;\n ctx.addIssue({\n code: \"custom\",\n path: [\"remote\", key],\n message: `remote.${key} applies only to a \"remote\" backend; this one is \"${backend.kind}\".`,\n });\n }\n }\n const url: unknown = backend.remote?.url;\n const graphqlRef = resolved ? undefined : endpointsGraphqlRef(url);\n if (graphqlRef) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"remote\", \"url\"],\n message: `remote.url reads ${graphqlRef.host}'s endpoints.graphql; it must be a switchboard drive address (<switchboard>/d/<slug>): sync needs the drive. Use ${useDriveUrl(graphqlRef.host, graphqlRef.member)}.`,\n });\n }\n if (resolved && typeof url === \"string\" && !switchboardOfDrive(url)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"remote\", \"url\"],\n message: `remote.url must be a switchboard drive address (<switchboard>/d/<slug>), not ${url}: sync needs the drive. Use ${useDriveUrl()}.`,\n });\n }\n const store = backend.storage;\n const storeDir = store?.kind === \"path\" ? store.dataDir : undefined;\n const readModel = backend.readModel?.url;\n // In the declared form dataDir may still be a `$env` token: compare\n // only resolved strings (resolved validation re-runs this check).\n if (\n typeof storeDir === \"string\" &&\n readModel &&\n samePath(storeDir, readModel)\n ) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"readModel\", \"url\"],\n message:\n `readModel.url must not be the reactor's storage dir (${readModel}): ` +\n \"two PGlite instances on one data dir corrupt it. Omit readModel.url \" +\n \"to get the classic <root>/.ph/read-storage next to the reactor store.\",\n });\n }\n });\n\n const reactorSchema = z\n .strictObject({\n backends: z.record(z.string(), reactorBackendSchema).optional(),\n placement: z\n .strictObject({\n primary: z.string().optional(),\n /** Declared drive slug → backend name. A local backend keeps a\n * synced copy; the drive's own remote backend opens it there with\n * no copy. An unlisted drive keeps a synced copy. */\n drives: z.record(z.string().min(1), z.string().min(1)).optional(),\n /** The backend new drives (and documents outside a drive) are\n * created on. A switchboard keeps no copy in this browser.\n * Default: the browser reactor, else the only switchboard. */\n newDrives: z.string().min(1).optional(),\n })\n .optional(),\n router: z\n .strictObject({\n /** Wait this long for a reactor to say whether it holds a\n * document. 0: no bound. Default 3_000. */\n probeTimeoutMs: z.number().int().nonnegative().optional(),\n /** Look again after this long for a document found on a later\n * backend. Default 30_000. */\n provisionalRouteMs: z.number().int().nonnegative().optional(),\n })\n .optional(),\n protocol: reactorProtocolSchema.optional(),\n // R1 core keys: identity/signing and storage namespace.\n renown: z\n .strictObject({\n url: z.string().optional(),\n networkId: z.string().optional(),\n chainId: z.number().int().optional(),\n })\n .optional(),\n namespace: z.string().min(1).optional(),\n // Core-declared, seeded by the host runtime. Token-able as a whole\n // (3.3): a `$map` over a producer's `drives` output (or an `$output` of\n // an array of declarations) renders the list at resolve time.\n drives: tokenField\n .any(z.array(buildDriveDeclarationSchema(tokenField.any)))\n .optional(),\n })\n .superRefine((reactor, ctx) => {\n const backends = reactor.backends ?? {};\n for (const [slug, name] of Object.entries(\n reactor.placement?.drives ?? {},\n )) {\n if (Object.hasOwn(backends, name)) continue;\n ctx.addIssue({\n code: \"custom\",\n path: [\"placement\", \"drives\", slug],\n message: `placement.drives.${slug} names backend \"${name}\", which is not in backends (${Object.keys(backends).join(\", \") || \"none\"}).`,\n });\n }\n const newDrives = reactor.placement?.newDrives;\n if (newDrives !== undefined && !Object.hasOwn(backends, newDrives)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"placement\", \"newDrives\"],\n message: `placement.newDrives names backend \"${newDrives}\", which is not in backends (${Object.keys(backends).join(\", \") || \"none\"}).`,\n });\n }\n if (resolved) refineResolvedReactor(reactor, ctx);\n });\n\n /** Common runner options; runner modules extend it with their own. */\n const runnerBaseSchema = z.looseObject({\n module: z.string().min(1),\n defaultVerb: z.string().min(1).optional(),\n port: z.number().int().positive().optional(),\n /** Bind address; each runner documents its default. */\n host: z.string().min(1).optional(),\n /** THE COMPOSITION: plugin entries; presence is activation. */\n plugins: z.array(pluginEntrySchema).optional(),\n });\n\n /** A compound member wrapper. Sections are FULL STATEMENTS except `runner`,\n * which key-merges over the member's own. Plugins live in `runner.plugins`\n * (as on a standalone host); there is no wrapper-level `plugins`. */\n const childWrapperSchema = z.strictObject({\n host: z.string().min(1).regex(HOST_REF_PATTERN, HOST_REF_MESSAGE),\n // 0 passes here; the member runner's own schema decides whether it may.\n runner: runnerBaseSchema\n .partial()\n .extend({ port: z.number().int().min(0).max(65535).optional() })\n .optional(),\n config: z.looseObject({}).optional(),\n reactor: reactorSchema.optional(),\n /** Where the member runs: `own`, a child process of the compound\n * (`ph run <host>`), stopped through its stdin; `shared`, in the\n * compound's own process. Default: `own` next to a foreground member\n * (the Cli runner), `shared` otherwise. */\n process: memberProcessSchema.optional(),\n });\n\n const childrenSchema = z.record(z.string(), childWrapperSchema);\n\n const reactorHostSchema = z.strictObject({\n name: hostNameSchema,\n runner: runnerBaseSchema,\n config: z.looseObject({}).optional(),\n profile: profileSchema.optional(),\n reactor: reactorSchema.optional(),\n });\n\n const compoundHostSchema = z.strictObject({\n name: hostNameSchema,\n runner: runnerBaseSchema,\n children: childrenSchema,\n config: z.looseObject({}).optional(),\n profile: profileSchema.optional(),\n });\n\n return {\n reactorBackendSchema,\n reactorSchema,\n runnerBaseSchema,\n childWrapperSchema,\n childrenSchema,\n reactorHostSchema,\n compoundHostSchema,\n /** This set's field wrapper, for a runner's OWN token-able fields inside\n * `defineHostSchemas`: declared, `T | Token` in and `T` out; resolved,\n * `T` only. Both modes share one static type. */\n tokenable: tokenField.any,\n /** As `tokenable`, but the only token accepted is `$env`. */\n envTokenable: tokenField.env,\n };\n}\n\nexport type HostSchemas = ReturnType<typeof buildHostSchemas>;\n\n/** The host schema set in declared (\"allow\": token-able fields take tokens)\n * or resolved (\"forbid\") form. */\nexport function makeHostSchemas(options: { tokens: TokenMode }): HostSchemas {\n return buildHostSchemas(\n options.tokens === \"allow\" ? ALLOW_TOKENS : FORBID_TOKENS,\n );\n}\n\nexport type PlacementKeyIssue = {\n path: (string | number)[];\n message: string;\n};\n\n/** The issues a host-level refinement raises, outside a zod parse. */\nfunction collectIssues(\n host: unknown,\n refine: (host: DeclaredReactorHost, ctx: z.RefinementCtx) => void,\n): PlacementKeyIssue[] {\n if (typeof host !== \"object\" || host === null || !(\"reactor\" in host)) {\n return [];\n }\n const issues: PlacementKeyIssue[] = [];\n const ctx = {\n addIssue: (issue: { path?: PropertyKey[]; message?: string }) => {\n issues.push({\n path: (issue.path ?? []).filter(\n (part): part is string | number => typeof part !== \"symbol\",\n ),\n message: issue.message ?? \"\",\n });\n },\n } as unknown as z.RefinementCtx;\n refine(host as DeclaredReactorHost, ctx);\n return issues;\n}\n\n/** withPlacementKeys' check, for a merged declared host parsed some other way. */\nexport function placementKeyIssues(host: unknown): PlacementKeyIssue[] {\n return collectIssues(host, refineDeclaredPlacementKeys);\n}\n\nexport const CONNECT_PRIMARY_MESSAGE =\n \"Connect doesn't use placement.primary. To choose where new drives go, use placement.newDrives.\";\n\n/**\n * A Connect host's placement rules, in either form. The router's primary is\n * the browser reactor, else the `newDrives` switchboard, else the only one,\n * so `placement.primary` means nothing here, and a Connect with several\n * switchboards and no browser reactor must say where new drives go. Apply it\n * last to the Connect runner's schema: `.superRefine(refineConnectReactor)`.\n */\nexport function refineConnectReactor(\n host: { reactor?: unknown },\n ctx: z.RefinementCtx,\n): void {\n const reactor = (host as DeclaredReactorHost).reactor;\n if (!reactor) return;\n if (reactor.placement?.primary !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"reactor\", \"placement\", \"primary\"],\n message: CONNECT_PRIMARY_MESSAGE,\n });\n }\n const backends = Object.entries(reactor.backends ?? {});\n const remotes = backends\n .filter(([, backend]) => backend.kind === \"remote\")\n .map(([name]) => name);\n if (\n remotes.length > 1 &&\n remotes.length === backends.length &&\n reactor.placement?.newDrives === undefined\n ) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"reactor\", \"placement\", \"newDrives\"],\n message: `This Connect keeps no reactor in the browser and links ${remotes.length} switchboards (${remotes.join(\", \")}). Set placement.newDrives to the one new drives are created on.`,\n });\n }\n}\n\n/** refineConnectReactor's check, for a Connect host parsed some other way. */\nexport function connectReactorIssues(host: unknown): PlacementKeyIssue[] {\n return collectIssues(host, refineConnectReactor);\n}\n\n/** Adds the host-level placement key check to a runner's declared schema. */\nfunction withPlacementKeys<T>(schema: T): T {\n if (!(schema instanceof z.ZodType)) return schema;\n return schema.superRefine((host, ctx) => {\n if (typeof host === \"object\" && host !== null && \"reactor\" in host) {\n refineDeclaredPlacementKeys(host as DeclaredReactorHost, ctx);\n }\n }) as T;\n}\n\n/**\n * One runner definition, two schemas (3.5): `build` runs over the DECLARED\n * set (tokens allowed; its z.input types host files) and the RESOLVED set\n * (no tokens; `validateHost` checks it before the verb). Export both, type\n * the host as `z.input<typeof declaredHostSchema>`, refine last inside the\n * builder (zod can't extend a refined object), and wrap the runner's own\n * token-able fields with `s.tokenable` / `s.envTokenable`.\n */\nexport function defineHostSchemas<T>(build: (schemas: HostSchemas) => T): {\n declaredHostSchema: T;\n hostSchema: T;\n} {\n return {\n declaredHostSchema: withPlacementKeys(build(declaredSchemas)),\n hostSchema: build(resolvedSchemas),\n };\n}\n\nconst declaredSchemas = makeHostSchemas({ tokens: \"allow\" });\nconst resolvedSchemas = makeHostSchemas({ tokens: \"forbid\" });\n\n/* The exported base blocks are the RESOLVED form (what verbs receive). The\n * declared forms are `declaredHostSchemas` / `defineHostSchemas`. */\nexport const declaredHostSchemas: HostSchemas = declaredSchemas;\nexport const reactorBackendSchema = resolvedSchemas.reactorBackendSchema;\nexport const reactorSchema = resolvedSchemas.reactorSchema;\nexport const runnerBaseSchema = resolvedSchemas.runnerBaseSchema;\nexport const childWrapperSchema = resolvedSchemas.childWrapperSchema;\nexport const childrenSchema = resolvedSchemas.childrenSchema;\nexport const reactorHostSchema = resolvedSchemas.reactorHostSchema;\nexport const compoundHostSchema = resolvedSchemas.compoundHostSchema;\n\n/** The generic compound runner's host: the base with its wiring config. */\nconst genericCompound = defineHostSchemas((s) =>\n s.compoundHostSchema\n .extend({ config: compoundWiringSchema.optional() })\n .superRefine(refineStartOrder),\n);\nexport const genericCompoundHostSchema = genericCompound.hostSchema;\nexport const declaredGenericCompoundHostSchema =\n genericCompound.declaredHostSchema;\n\n/* -------------------------------------------------------------------- types */\n\nexport type Profile = z.infer<typeof profileSchema>;\nexport type ReactorProtocol = z.infer<typeof reactorProtocolSchema>;\nexport type ReactorBackend = z.infer<typeof reactorBackendSchema>;\nexport type ReactorBackendKind = ReactorBackend[\"kind\"];\nexport type ReactorStorageConfig = NonNullable<ReactorBackend[\"storage\"]>;\nexport type ReactorPackageConfig = NonNullable<ReactorBackend[\"packages\"]>;\nexport type ReactorRemoteConfig = NonNullable<ReactorBackend[\"remote\"]>;\nexport type ReactorConfig = z.infer<typeof reactorSchema>;\nexport type RunnerBase = z.infer<typeof runnerBaseSchema>;\nexport type ChildWrapper = z.infer<typeof childWrapperSchema>;\nexport type CompoundWiring = z.infer<typeof compoundWiringSchema>;\n\n/** What a host.js author writes (z.input), per runner kind. The `never`\n * sides make reactor XOR children a type error. */\nexport type ReactorHostInput = z.input<\n typeof declaredSchemas.reactorHostSchema\n> & {\n children?: never;\n};\nexport type CompoundHostInput = z.input<\n typeof declaredSchemas.compoundHostSchema\n> & {\n reactor?: never;\n};\nexport type HostDefinition = ReactorHostInput | CompoundHostInput;\n\n/** What a verb receives (z.output) from the base schemas. */\nexport type ReactorHost = z.output<typeof reactorHostSchema>;\nexport type CompoundHost = z.output<typeof compoundHostSchema>;\n\n/* --------------------------------------------------------------- JSON Schema */\n\nconst SCHEMA_BASE = \"https://powerhouse.inc/schemas\";\n\n/** One host schema as an editor JSON Schema with a stable `$id` — the\n * per-runner emission helper (runner packages emit their own hostSchema). */\nexport function emitHostJsonSchema(\n name: string,\n schema: z.ZodType,\n): Record<string, unknown> {\n return {\n $id: `${SCHEMA_BASE}/${name}.schema.json`,\n ...z.toJSONSchema(schema, { io: \"input\" }),\n };\n}\n\n/** The emitted-schema set, keyed by published filename. Pure — the\n * emit-schemas script writes these and the drift test re-derives them. */\nexport function emittedHostSchemas(): Record<string, unknown> {\n return {\n // Editor schemas describe what authors write: the declared form.\n \"host-reactor.schema.json\": emitHostJsonSchema(\n \"host-reactor\",\n declaredSchemas.reactorHostSchema,\n ),\n \"host-compound.schema.json\": emitHostJsonSchema(\n \"host-compound\",\n declaredSchemas.compoundHostSchema,\n ),\n };\n}\n","import path from \"node:path\";\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\n/**\n * What names one running instance at every layer (host runs, Cli services,\n * the desktop shell): a host and a data folder. The same key asked twice is\n * one instance; two data folders are two instances of the host.\n */\nexport interface InstanceKey {\n /** The host as `ph run` addresses it: its name, behind its package when an\n * installed package supplies it (`@acme/tools/studio`). */\n host: string;\n /** The folder that holds the instance's `.ph` tree: PH_USER_DATA_DIR when\n * set (a desktop shell's per-user folder), else the project folder. */\n dataDir: string;\n /** Both in one string, equal for equal keys. */\n id: string;\n}\n\n/** The data folder of a project: where its `.ph` tree is. */\nexport function instanceDataDir(\n projectDir: string = process.cwd(),\n env: Env = process.env,\n): string {\n return path.resolve(env.PH_USER_DATA_DIR ?? projectDir);\n}\n\n/** The key of `host` (a record key, see `runRecordKey`) in a project. */\nexport function instanceKey(\n host: string,\n projectDir: string = process.cwd(),\n env: Env = process.env,\n): InstanceKey {\n const dataDir = instanceDataDir(projectDir, env);\n // Windows paths name one folder in any case.\n const folder = process.platform === \"win32\" ? dataDir.toLowerCase() : dataDir;\n return { host, dataDir, id: `${host}@${folder}` };\n}\n\n/** The `.ph` tree of a data folder. */\nexport function instancePhDir(key: Pick<InstanceKey, \"dataDir\">): string {\n return path.join(key.dataDir, \".ph\");\n}\n\n/** Where the run records of a data folder are: the one place they are kept. */\nexport function instanceRunDir(key: Pick<InstanceKey, \"dataDir\">): string {\n return path.join(instancePhDir(key), \"run\");\n}\n\n/** Where a Cli keeps the state of its services: under the data folder, so\n * two project folders never see each other's. */\nexport function instanceServicesDir(\n key: Pick<InstanceKey, \"dataDir\">,\n cliName: string,\n): string {\n return path.join(instancePhDir(key), cliName, \"services\");\n}\n","import { z } from \"zod\";\nimport {\n hostNameSchema,\n PACKAGE_NAME_PATTERN,\n runnerKindSchema,\n} from \"./host-schemas.js\";\n\n/**\n * `.ph/run/<host>.json`, version 2 (typed-host-configs 3.6): what a running\n * host and its members produced. Validated on read; a v1 (or any invalid)\n * record reads as \"not running\". `projectName` is kept beyond the plan's\n * sketch because the live/foreign probe needs it. `host` is the host's\n * `name` (the file key), not its folder. A host an installed package\n * supplies has its record in a folder named after the package,\n * `.ph/run/<package>/<host>.json`, and says which in `package`.\n */\n\nconst outputsSchema = z.record(z.string(), z.unknown());\n\nexport const runRecordMemberSchema = z.strictObject({\n /** The member's host as the project addresses it: its folder, or\n * `<package>/<host>` for one a package supplies. */\n host: z.string().min(1),\n runnerModule: z.string().min(1),\n kind: runnerKindSchema,\n verb: z.string().min(1),\n outputs: outputsSchema,\n});\n\nexport const runRecordSchema = z.strictObject({\n version: z.literal(2),\n host: hostNameSchema,\n /** The installed package that supplies the host; absent for the\n * project's own. */\n package: z.string().regex(PACKAGE_NAME_PATTERN).optional(),\n projectName: z.string(),\n kind: runnerKindSchema,\n verb: z.string().min(1),\n pid: z.number().int(),\n startedAt: z.string(),\n /** Standalone hosts: the runner's outputs. */\n outputs: outputsSchema.optional(),\n /** Compounds: one entry per started member, keyed by member name. */\n members: z.record(z.string(), runRecordMemberSchema).optional(),\n /** Host-specific extras (e.g. mcpUrl) a runner wants in the record. */\n extra: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type RunRecord = z.infer<typeof runRecordSchema>;\nexport type RunRecordMember = z.infer<typeof runRecordMemberSchema>;\n","import { execFileSync } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n HOST_NAME_MESSAGE,\n hostNameSchema,\n PACKAGE_NAME_PATTERN,\n} from \"./host-schemas.js\";\nimport { instanceKey, instanceRunDir } from \"./instance-key.js\";\nimport { writeOwnerOnlyFile } from \"./owner-only.js\";\nimport { runRecordSchema, type RunRecord } from \"./run-record-schema.js\";\n\nexport {\n runRecordMemberSchema,\n runRecordSchema,\n type RunRecord,\n type RunRecordMember,\n} from \"./run-record-schema.js\";\n\n/**\n * Record I/O for `.ph/run/<host>.json`, keyed by host name so N hosts\n * (vetra, desktop, …) coexist. The record shape is run-record-schema.ts (v2).\n * A host an installed package supplies is keyed `<package>/<name>`\n * ({@link runRecordKey}) and filed in a folder named after the package,\n * `.ph/run/@scope/pkg/<name>.json`, so it never meets a project host of the\n * same name. The functions below take either key.\n */\n\nexport type RunProbe =\n | { status: \"none\" }\n | { status: \"stale\"; record: RunRecord }\n | { status: \"live\"; record: RunRecord }\n | { status: \"foreign\"; record: RunRecord };\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\n/** The key a host's record is filed under: its `name`, behind the package\n * that supplies it when it is not the project's own (`@acme/tools/studio`),\n * as `ph run` addresses the host. */\nexport function runRecordKey(name: string, hostPackage?: string): string {\n return hostPackage === undefined ? name : `${hostPackage}/${name}`;\n}\n\n/** The key of a record as read: where it is filed. */\nexport function recordKeyOf(record: Pick<RunRecord, \"host\" | \"package\">) {\n return runRecordKey(record.host, record.package);\n}\n\n// Under the data folder's .ph tree — relocated with it by PH_USER_DATA_DIR.\n// The readers take `env` so a launcher can read a child's records.\nconst runDir = (projectDir: string, env: Env = process.env) =>\n instanceRunDir(instanceKey(\"\", projectDir, env));\n\n/** The file of an instance's record: `(host, data folder)` is its path. */\nexport function runRecordPath(\n projectDir: string,\n key: string,\n env?: Env,\n): string {\n return recordPath(projectDir, key, env);\n}\nfunction recordPath(projectDir: string, key: string, env?: Env): string {\n const dir = runDir(projectDir, env);\n const slash = key.lastIndexOf(\"/\");\n const hostName = key.slice(slash + 1);\n const pkg = slash === -1 ? undefined : key.slice(0, slash);\n const folder =\n pkg === undefined\n ? path.resolve(dir)\n : path.resolve(dir, ...pkg.split(\"/\"));\n const file = path.resolve(folder, `${hostName}.json`);\n if (\n !hostNameSchema.safeParse(hostName).success ||\n (pkg !== undefined && !PACKAGE_NAME_PATTERN.test(pkg)) ||\n path.dirname(file) !== folder\n ) {\n throw new Error(`\"${key}\" can't name a run record. ${HOST_NAME_MESSAGE}`);\n }\n return file;\n}\n\n/** The record keys under `.ph/run/`: `<name>.json` files, and those in a\n * package's folder (`<pkg>/` or `@scope/<pkg>/`). */\nfunction recordKeys(dir: string): string[] {\n const entries = (at: string) => {\n try {\n return fs.readdirSync(at, { withFileTypes: true });\n } catch {\n return [];\n }\n };\n const records = (at: string, prefix: string) =>\n entries(at)\n .filter((entry) => entry.isFile() && entry.name.endsWith(\".json\"))\n .map((entry) => `${prefix}${entry.name.slice(0, -\".json\".length)}`);\n const keys = records(dir, \"\");\n for (const entry of entries(dir)) {\n if (!entry.isDirectory()) continue;\n const at = path.join(dir, entry.name);\n if (!entry.name.startsWith(\"@\")) {\n keys.push(...records(at, `${entry.name}/`));\n continue;\n }\n for (const inner of entries(at)) {\n if (!inner.isDirectory()) continue;\n keys.push(\n ...records(path.join(at, inner.name), `${entry.name}/${inner.name}/`),\n );\n }\n }\n return keys;\n}\n\nexport function readRunRecord(\n projectDir: string,\n hostName: string,\n env: Env = process.env,\n): RunRecord | undefined {\n let raw: unknown;\n try {\n raw = JSON.parse(\n fs.readFileSync(recordPath(projectDir, hostName, env), \"utf8\"),\n );\n } catch {\n return undefined;\n }\n // v1 and foreign-shaped records read as \"not running\" (3.6).\n const parsed = runRecordSchema.safeParse(raw);\n return parsed.success ? parsed.data : undefined;\n}\n\n/** Every valid v2 record under `.ph/run/`, package hosts' included (invalid\n * and v1 files skipped). */\nexport function listRunRecords(\n projectDir: string,\n env: Env = process.env,\n): RunRecord[] {\n return recordKeys(runDir(projectDir, env)).flatMap((key) => {\n const record = readRunRecord(projectDir, key, env);\n return record ? [record] : [];\n });\n}\n\n/** The project identity the live/foreign probe compares: package.json\n * `name`, else the folder name. */\nexport function readProjectName(projectDir: string): string {\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(projectDir, \"package.json\"), \"utf8\"),\n ) as { name?: unknown };\n if (typeof pkg.name === \"string\" && pkg.name) return pkg.name;\n } catch {\n // fall through\n }\n return path.basename(path.resolve(projectDir));\n}\n\nexport function writeRunRecord(projectDir: string, record: RunRecord): void {\n const target = recordPath(projectDir, recordKeyOf(record));\n const valid = runRecordSchema.parse(record);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n const text = `${JSON.stringify(valid, null, 2)}\\n`;\n if (valid.extra?.control === undefined && valid.extra?.signIn === undefined) {\n fs.writeFileSync(target, text);\n return;\n }\n // It holds the control channel's token or the sign-in secret: the user's\n // alone.\n writeOwnerOnlyFile(target, text);\n}\n\nexport function clearRunRecord(\n projectDir: string,\n hostName: string,\n env: Env = process.env,\n): void {\n try {\n fs.rmSync(recordPath(projectDir, hostName, env));\n } catch {\n // already gone\n }\n}\n\nexport function isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM = the process exists but belongs to another user.\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/** When a process started, in ms since the epoch; undefined when the\n * platform does not tell (the process is gone, the tool is missing). */\nexport function processStartedAtMs(pid: number): number | undefined {\n try {\n if (process.platform === \"linux\") {\n // Field 22 of /proc/<pid>/stat: start in clock ticks (100 a second)\n // after boot; the command (field 2) may hold spaces, so count from\n // its closing bracket.\n const stat = fs.readFileSync(`/proc/${pid}/stat`, \"utf8\");\n const ticks = Number(\n stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \")[19],\n );\n const boot = /^btime (\\d+)$/m.exec(fs.readFileSync(\"/proc/stat\", \"utf8\"));\n if (!boot || !Number.isFinite(ticks)) return undefined;\n return (Number(boot[1]) + ticks / 100) * 1000;\n }\n const [command, args] =\n process.platform === \"win32\"\n ? [\n \"powershell.exe\",\n [\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-Command\",\n `(Get-Process -Id ${pid}).StartTime.ToUniversalTime().ToString('o')`,\n ],\n ]\n : [\"ps\", [\"-o\", \"lstart=\", \"-p\", String(pid)]];\n const out = execFileSync(command, args, {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: 10_000,\n windowsHide: true,\n env: { ...process.env, LC_ALL: \"C\" },\n }).trim();\n const started = Date.parse(out);\n return Number.isFinite(started) ? started : undefined;\n } catch {\n return undefined;\n }\n}\n\n// A record is written by the process it names, so that process started\n// before `startedAt`. The slack covers clocks that count in seconds.\nconst START_SLACK_MS = 5_000;\n// The records whose pid was found to be the recording process: asked once\n// per record, since the answer costs a child process on Windows and macOS.\nconst confirmedRecords = new Set<string>();\n\n/** True when the recorded pid now names another process: one that started\n * after the record was written. False when that cannot be told. */\nfunction isPidReused(record: RunRecord): boolean {\n if (record.pid === process.pid) return false;\n const recordedAt = Date.parse(record.startedAt);\n if (!Number.isFinite(recordedAt)) return false;\n const key = `${record.pid}:${record.startedAt}`;\n if (confirmedRecords.has(key)) return false;\n const startedAt = processStartedAtMs(record.pid);\n if (startedAt === undefined) return false;\n if (startedAt > recordedAt + START_SLACK_MS) return true;\n confirmedRecords.add(key);\n return false;\n}\n\n/**\n * Decide whether the recorded instance is this project's live host.\n *\n * pid liveness alone proves nothing (pids are reused): a live pid counts\n * only when its process started before the record was written. The recorded\n * projectName is what separates \"my instance\" from \"a different project that\n * happens to hold this storage root\" — the confusion the vetra lock exists to\n * prevent. A stale record (dead or reused pid) is reported so the caller can\n * clear it; a foreign one (live pid, different project) is left alone.\n */\nexport function probeRun(\n projectDir: string,\n hostName: string,\n projectName: string,\n env: Env = process.env,\n): RunProbe {\n const record = readRunRecord(projectDir, hostName, env);\n if (!record) return { status: \"none\" };\n if (!isPidAlive(record.pid) || isPidReused(record)) {\n return { status: \"stale\", record };\n }\n if (record.projectName !== projectName) return { status: \"foreign\", record };\n return { status: \"live\", record };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAWA,SAAgB,4BACd,UACA;CACA,OAAO,EAAE,aAAa;EACpB,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;EACtB,IAAI,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;;;;;;EAM/B,aAAa,EAAE,MAAM,CAAC,EAAE,QAAQ,GAAG,EAAE,QAAQ,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS;;EAE9D,cAAc,EACX,KAAK,CAAC,6BAA6B,0BAA0B,CAAC,CAAC,CAC/D,SAAS;EACZ,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;EACjC,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS;EAC1B,iBAAiB,EAAE,OAAO,CAAC,CAAC,SAAS;EACrC,aAAa,EAAE,KAAK;GAAC;GAAU;GAAW;EAAQ,CAAC,CAAC,CAAC,SAAS;EAC9D,kBAAkB,EAAE,QAAQ,CAAC,CAAC,SAAS;EACvC,QAAQ,EAAE,aAAa,EAAE,KAAK,SAAS,EAAE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,cAAc,KAAA,GAAW,OAAO;CACpC,IAAI,YAAY,aAAa,gBAAgB,OAAO;CACpD,iBAAiB,IAAI,GAAG;CACxB,OAAO;AACT;;;;;;;;;;;AAYA,SAAgB,SACd,YACA,UACA,aACA,MAAW,QAAQ,KACT;CACV,MAAM,SAAS,cAAc,YAAY,UAAU,GAAG;CACtD,IAAI,CAAC,QAAQ,OAAO,EAAE,QAAQ,OAAO;CACrC,IAAI,CAAC,WAAW,OAAO,GAAG,KAAK,YAAY,MAAM,GAC/C,OAAO;EAAE,QAAQ;EAAS;CAAO;CAEnC,IAAI,OAAO,gBAAgB,aAAa,OAAO;EAAE,QAAQ;EAAW;CAAO;CAC3E,OAAO;EAAE,QAAQ;EAAQ;CAAO;AAClC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { I as RunnerContext, a as RunCompoundResult, bt as HostDefinition } from "../compound-
|
|
1
|
+
import { I as RunnerContext, a as RunCompoundResult, bt as HostDefinition } from "../compound-BLhEewO6.mjs";
|
|
2
2
|
//#region src/runners/compound.d.ts
|
|
3
3
|
/**
|
|
4
4
|
* The GENERIC compound runner module (phase 3): supervises the members a
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { B as genericCompoundHostSchema, F as declaredGenericCompoundHostSchema, o as readProjectName } from "../run-record-C6oTZF_C.mjs";
|
|
2
|
+
import { l as runCompound, n as compoundStartVerb, u as stopStreamOf } from "../compound-g6x_KkWp.mjs";
|
|
2
3
|
//#region src/runners/compound.ts
|
|
3
4
|
/**
|
|
4
5
|
* The GENERIC compound runner module (phase 3): supervises the members a
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compound.mjs","names":[],"sources":["../../src/runners/compound.ts"],"sourcesContent":["import {\n declaredGenericCompoundHostSchema,\n genericCompoundHostSchema,\n type HostDefinition,\n} from \"../host-schemas.js\";\nimport {\n compoundStartVerb,\n runCompound,\n stopStreamOf,\n type RunCompoundResult,\n} from \"../compound.js\";\nimport { readProjectName } from \"../run-record.js\";\nimport type { RunnerContext } from \"../runner-resolver.js\";\n\n/**\n * The GENERIC compound runner module (phase 3): supervises the members a\n * compound host declares via the runCompound engine. Verb semantics: `run`\n * starts members at `runner.defaultVerb ?? \"run\"`; `dev`/`build`/`serve`\n * start members at that same verb — an explicit `ph run <host> <verb>` beats\n * defaultVerb structurally. A member whose runner lacks the forwarded verb\n * fails the compound loudly with that member's verb list (never skipped).\n *\n * Vetra does NOT run through this yet (phase-1 scope decision: its drive\n * provisioning arrives as plugin contributions); the first real consumer is\n * the desktop-shaped host (switchboard `run` + connect `serve`).\n */\n\nexport const kind = \"compound\";\n\nexport const hostSchema = genericCompoundHostSchema;\nexport const declaredHostSchema = declaredGenericCompoundHostSchema;\n\nasync function startAt(\n host: HostDefinition,\n ctx: RunnerContext,\n memberVerb: string,\n): Promise<RunCompoundResult> {\n return runCompound(\n host,\n { ...ctx, verb: memberVerb },\n {\n projectName: readProjectName(ctx.projectRoot),\n stopStream: stopStreamOf(process.env, () => process.stdin),\n },\n );\n}\n\nexport async function run(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<RunCompoundResult> {\n return startAt(host, ctx, compoundStartVerb(\"run\", host.runner));\n}\n\nexport async function dev(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<RunCompoundResult> {\n return startAt(host, ctx, \"dev\");\n}\n\nexport async function build(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<RunCompoundResult> {\n return startAt(host, ctx, \"build\");\n}\n\nexport async function serve(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<RunCompoundResult> {\n return startAt(host, ctx, \"serve\");\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"compound.mjs","names":[],"sources":["../../src/runners/compound.ts"],"sourcesContent":["import {\n declaredGenericCompoundHostSchema,\n genericCompoundHostSchema,\n type HostDefinition,\n} from \"../host-schemas.js\";\nimport {\n compoundStartVerb,\n runCompound,\n stopStreamOf,\n type RunCompoundResult,\n} from \"../compound.js\";\nimport { readProjectName } from \"../run-record.js\";\nimport type { RunnerContext } from \"../runner-resolver.js\";\n\n/**\n * The GENERIC compound runner module (phase 3): supervises the members a\n * compound host declares via the runCompound engine. Verb semantics: `run`\n * starts members at `runner.defaultVerb ?? \"run\"`; `dev`/`build`/`serve`\n * start members at that same verb — an explicit `ph run <host> <verb>` beats\n * defaultVerb structurally. A member whose runner lacks the forwarded verb\n * fails the compound loudly with that member's verb list (never skipped).\n *\n * Vetra does NOT run through this yet (phase-1 scope decision: its drive\n * provisioning arrives as plugin contributions); the first real consumer is\n * the desktop-shaped host (switchboard `run` + connect `serve`).\n */\n\nexport const kind = \"compound\";\n\nexport const hostSchema = genericCompoundHostSchema;\nexport const declaredHostSchema = declaredGenericCompoundHostSchema;\n\nasync function startAt(\n host: HostDefinition,\n ctx: RunnerContext,\n memberVerb: string,\n): Promise<RunCompoundResult> {\n return runCompound(\n host,\n { ...ctx, verb: memberVerb },\n {\n projectName: readProjectName(ctx.projectRoot),\n stopStream: stopStreamOf(process.env, () => process.stdin),\n },\n );\n}\n\nexport async function run(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<RunCompoundResult> {\n return startAt(host, ctx, compoundStartVerb(\"run\", host.runner));\n}\n\nexport async function dev(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<RunCompoundResult> {\n return startAt(host, ctx, \"dev\");\n}\n\nexport async function build(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<RunCompoundResult> {\n return startAt(host, ctx, \"build\");\n}\n\nexport async function serve(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<RunCompoundResult> {\n return startAt(host, ctx, \"serve\");\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2BA,MAAa,OAAO;AAEpB,MAAa,aAAa;AAC1B,MAAa,qBAAqB;AAElC,eAAe,QACb,MACA,KACA,YAC4B;CAC5B,OAAO,YACL,MACA;EAAE,GAAG;EAAK,MAAM;CAAW,GAC3B;EACE,aAAa,gBAAgB,IAAI,WAAW;EAC5C,YAAY,aAAa,QAAQ,WAAW,QAAQ,KAAK;CAC3D,CACF;AACF;AAEA,eAAsB,IACpB,MACA,KAC4B;CAC5B,OAAO,QAAQ,MAAM,KAAK,kBAAkB,OAAO,KAAK,MAAM,CAAC;AACjE;AAEA,eAAsB,IACpB,MACA,KAC4B;CAC5B,OAAO,QAAQ,MAAM,KAAK,KAAK;AACjC;AAEA,eAAsB,MACpB,MACA,KAC4B;CAC5B,OAAO,QAAQ,MAAM,KAAK,OAAO;AACnC;AAEA,eAAsB,MACpB,MACA,KAC4B;CAC5B,OAAO,QAAQ,MAAM,KAAK,OAAO;AACnC"}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { w as RunRecord } from "./control-channel-DVn4dvfQ.mjs";
|
|
2
|
+
//#region src/compound-member.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* How a compound hands an own-process member its host. The member's
|
|
5
|
+
* `host.js` alone is not the member: the compound's wrapper (reactor, config
|
|
6
|
+
* and runner overrides) and its resolved tokens are. So the compound
|
|
7
|
+
* resolves the member as it would in its own process and the child's
|
|
8
|
+
* `ph run <folder>` runs that host instead of reading the file.
|
|
9
|
+
*/
|
|
10
|
+
/** Carries a {@link CompoundMemberHost} as JSON to the child's `ph run`. */
|
|
11
|
+
declare const COMPOUND_MEMBER_ENV = "PH_COMPOUND_MEMBER";
|
|
12
|
+
interface CompoundMemberHost {
|
|
13
|
+
/** The compound host's name. */
|
|
14
|
+
compound: string;
|
|
15
|
+
/** The member's key in the compound's `children`. */
|
|
16
|
+
member: string;
|
|
17
|
+
/** The member's host folder: the child's `ph run <folder>`. */
|
|
18
|
+
folder: string;
|
|
19
|
+
/** The member's host, its wrapper applied and its tokens resolved. */
|
|
20
|
+
host: Record<string, unknown>;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The member host a compound handed this process for `folder`, taken out of
|
|
24
|
+
* `env` so nothing this process starts inherits it. Undefined when there is
|
|
25
|
+
* none; throws when it is malformed or names another folder.
|
|
26
|
+
*/
|
|
27
|
+
declare function takeCompoundMember(env: Record<string, string | undefined>, folder: string): CompoundMemberHost | undefined;
|
|
28
|
+
//#endregion
|
|
29
|
+
//#region src/spawn-host.d.ts
|
|
30
|
+
interface SpawnHostOptions {
|
|
31
|
+
projectRoot: string;
|
|
32
|
+
/** Folder name under hosts/, or `<package>/<host>` for a host an
|
|
33
|
+
* installed package supplies: what the child's `ph run` takes. */
|
|
34
|
+
host: string;
|
|
35
|
+
/** The child's PH_USER_DATA_DIR (created if missing). */
|
|
36
|
+
dataDir: string;
|
|
37
|
+
verb?: string;
|
|
38
|
+
/** What follows `ph run <host> [verb]`: the runner's arguments. */
|
|
39
|
+
argv?: readonly string[];
|
|
40
|
+
/** Merged over the base env; may not set PH_USER_DATA_DIR. */
|
|
41
|
+
env?: Record<string, string>;
|
|
42
|
+
/** The env the child starts from instead of the clean one, as it is: a
|
|
43
|
+
* compound hands its members its own, so a member sees what it would in
|
|
44
|
+
* the compound's process. */
|
|
45
|
+
baseEnv?: Readonly<Record<string, string | undefined>>;
|
|
46
|
+
/** The host the child runs instead of reading `hosts/<host>/host.js`: a
|
|
47
|
+
* compound's member, its wrapper applied and its tokens resolved. */
|
|
48
|
+
definition?: Omit<CompoundMemberHost, "folder">;
|
|
49
|
+
/** Ask the child to stop through its stdin (it gets a pipe and
|
|
50
|
+
* PH_STOP_ON_STDIN=1): a request on every platform, which this process
|
|
51
|
+
* ending makes too; after stopTimeoutMs its whole process tree is killed.
|
|
52
|
+
* Without it a stop is SIGTERM, on Windows the kill itself, and SIGKILL of
|
|
53
|
+
* the child follows after stopTimeoutMs. */
|
|
54
|
+
stopOnStdin?: boolean;
|
|
55
|
+
/** ph-cli entry; default: the project's `@powerhousedao/ph-cli/dist/cli.mjs`. */
|
|
56
|
+
cli?: string;
|
|
57
|
+
readyTimeoutMs?: number;
|
|
58
|
+
stopTimeoutMs?: number;
|
|
59
|
+
/** Before ready: stop and reject. After: stop. */
|
|
60
|
+
signal?: AbortSignal;
|
|
61
|
+
onOutput?: (stream: "stdout" | "stderr", chunk: string) => void;
|
|
62
|
+
/** Appends both streams. */
|
|
63
|
+
logFile?: string;
|
|
64
|
+
}
|
|
65
|
+
interface HostExit {
|
|
66
|
+
code: number | null;
|
|
67
|
+
signal: NodeJS.Signals | null;
|
|
68
|
+
/** SIGKILL after stopTimeoutMs. */
|
|
69
|
+
forced: boolean;
|
|
70
|
+
}
|
|
71
|
+
interface SpawnedHost {
|
|
72
|
+
pid: number;
|
|
73
|
+
dataDir: string;
|
|
74
|
+
record: RunRecord;
|
|
75
|
+
outputs: Record<string, unknown> | undefined;
|
|
76
|
+
members: RunRecord["members"];
|
|
77
|
+
/** The key ran already: this is that instance, and nothing was started.
|
|
78
|
+
* Its `stop()` leaves it running (its starter owns it; `ph run <host>
|
|
79
|
+
* --stop` stops it). */
|
|
80
|
+
existing?: true;
|
|
81
|
+
/** Resolves (never rejects) when the child exits. */
|
|
82
|
+
exited: Promise<HostExit>;
|
|
83
|
+
/** SIGTERM (or the end of its stdin), SIGKILL after stopTimeoutMs, clear
|
|
84
|
+
* a leftover record. */
|
|
85
|
+
stop(): Promise<HostExit>;
|
|
86
|
+
}
|
|
87
|
+
type SpawnHostPhase = "exited" | "timeout" | "aborted";
|
|
88
|
+
/** The tail line before which a timed-out or aborted run's output is its own. */
|
|
89
|
+
declare const SPAWN_STOPPING_NOTE = "spawnHost: stopping it";
|
|
90
|
+
declare class SpawnHostError extends Error {
|
|
91
|
+
readonly phase: SpawnHostPhase;
|
|
92
|
+
readonly outputTail: string;
|
|
93
|
+
readonly exit?: HostExit | undefined;
|
|
94
|
+
constructor(message: string, phase: SpawnHostPhase, outputTail: string, exit?: HostExit | undefined);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* `ph run <host> [verb]` as a child; ready when its run record appears.
|
|
98
|
+
*
|
|
99
|
+
* The child shares this process's group, so a terminal Ctrl-C reaches both.
|
|
100
|
+
* It runs the project's own ph-cli (else its ph-run): one older than
|
|
101
|
+
* PH_NO_DOTENV reads the project's `.env` anyway.
|
|
102
|
+
*/
|
|
103
|
+
declare function spawnHost(options: SpawnHostOptions): Promise<SpawnedHost>;
|
|
104
|
+
//#endregion
|
|
105
|
+
export { SpawnHostPhase as a, COMPOUND_MEMBER_ENV as c, SpawnHostOptions as i, CompoundMemberHost as l, SPAWN_STOPPING_NOTE as n, SpawnedHost as o, SpawnHostError as r, spawnHost as s, HostExit as t, takeCompoundMember as u };
|
|
106
|
+
export {};
|
|
107
|
+
//# sourceMappingURL=spawn-host-DWroRe1S.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"spawn-host-DWroRe1S.d.mts","names":[],"sources":["../src/compound-member.ts","../src/spawn-host.ts"],"mappings":";;;;;;;;;;cAYa;UAOI;;EAEf;;EAEA;;EAEA;;EAEA,MAAM;;;;;;;iBAmIQ,mBACd,KAAK,oCACL,iBACC;;;UCpIc;EACf;;;EAGA;;EAEA;EACA;;EAEA;;EAEA,MAAM;;;;EAIN,UAAU,SAAS;;;EAGnB,aAAa,KAAK;;;;;;EAMlB;;EAEA;EACA;EACA;;EAEA,SAAS;EACT,YAAY,6BAA6B;;EAEzC;;UAGe;EACf;EACA,QAAQ,OAAO;;EAEf;;UAGe;EACf;EACA;EACA,QAAQ;EACR,SAAS;EACT,SAAS;;;;EAIT;;EAEA,QAAQ,QAAQ;;;EAGhB,QAAQ,QAAQ;;KA6BN;;cAGC;cAEA,uBAAuB;WAGvB,OAAO;WACP;WACA,OAAO;EAJlB,YACE,iBACS,OAAO,gBACP,oBACA,OAAO;;;;;;;;;iBA0FE,UACpB,SAAS,mBACR,QAAQ"}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
//#region src/supervisor-record.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Where the supervisor of an OS user records itself, and how a tool of that
|
|
5
|
+
* user finds it without knowing a project. One folder per user:
|
|
6
|
+
*
|
|
7
|
+
* supervisor.json the running supervisor: its process and its control
|
|
8
|
+
* channel (address and token; the user's alone)
|
|
9
|
+
* supervisor.lock the process that is, or is becoming, the supervisor
|
|
10
|
+
* logs/ the output of instances started without a log file
|
|
11
|
+
*
|
|
12
|
+
* This module reads only: it starts nothing.
|
|
13
|
+
*/
|
|
14
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
15
|
+
/** Names another folder than `~/.ph/supervisor` (tests, a second user data
|
|
16
|
+
* root). */
|
|
17
|
+
export declare const SUPERVISOR_HOME_ENV = "PH_SUPERVISOR_HOME";
|
|
18
|
+
/** The supervisor's folder of this OS user. */
|
|
19
|
+
export declare function supervisorHome(env?: Env): string;
|
|
20
|
+
export declare function supervisorRecordPath(env?: Env): string;
|
|
21
|
+
export declare function supervisorLockPath(env?: Env): string;
|
|
22
|
+
/** `standalone`: `ph run supervisor` in a terminal. `installed`: started at
|
|
23
|
+
* login. */
|
|
24
|
+
export type SupervisorMode = "standalone" | "installed";
|
|
25
|
+
export declare const supervisorRecordSchema: z.ZodObject<{
|
|
26
|
+
version: z.ZodLiteral<1>;
|
|
27
|
+
pid: z.ZodNumber;
|
|
28
|
+
startedAt: z.ZodString;
|
|
29
|
+
supervisorVersion: z.ZodString;
|
|
30
|
+
mode: z.ZodString;
|
|
31
|
+
user: z.ZodString;
|
|
32
|
+
control: z.ZodObject<{
|
|
33
|
+
protocol: z.ZodNumber;
|
|
34
|
+
address: z.ZodString;
|
|
35
|
+
token: z.ZodString;
|
|
36
|
+
}, z.core.$strip>;
|
|
37
|
+
}, z.core.$strip>;
|
|
38
|
+
export type SupervisorRecord = z.infer<typeof supervisorRecordSchema>;
|
|
39
|
+
/** What a supervisor answers to `hello`. */
|
|
40
|
+
export interface SupervisorHello {
|
|
41
|
+
supervisor: true;
|
|
42
|
+
protocol: number;
|
|
43
|
+
pid: number;
|
|
44
|
+
mode: string;
|
|
45
|
+
version: string;
|
|
46
|
+
methods: string[];
|
|
47
|
+
}
|
|
48
|
+
export type FoundSupervisor =
|
|
49
|
+
/** None is recorded, or the recorded one has ended. */
|
|
50
|
+
{
|
|
51
|
+
status: "none";
|
|
52
|
+
} | {
|
|
53
|
+
status: "running";
|
|
54
|
+
record: SupervisorRecord;
|
|
55
|
+
hello: SupervisorHello;
|
|
56
|
+
} |
|
|
57
|
+
/** One is recorded and does not answer: nothing may be started beside it. */
|
|
58
|
+
{
|
|
59
|
+
status: "silent";
|
|
60
|
+
pid: number;
|
|
61
|
+
reason: string;
|
|
62
|
+
};
|
|
63
|
+
/** The supervisor's record as written; undefined when there is none, or it
|
|
64
|
+
* cannot be read. */
|
|
65
|
+
export declare function readSupervisorRecord(env?: Env): SupervisorRecord | undefined;
|
|
66
|
+
/** Whether a supervisor is recorded at all: one file read, for a tool that
|
|
67
|
+
* otherwise has nothing to ask. */
|
|
68
|
+
export declare function supervisorRecorded(env?: Env): boolean;
|
|
69
|
+
/** The process a lock file names, when it still runs. */
|
|
70
|
+
export declare function supervisorLockHolder(env?: Env): {
|
|
71
|
+
pid: number;
|
|
72
|
+
startedAt: string;
|
|
73
|
+
} | undefined;
|
|
74
|
+
/** How a tool is told that the recorded supervisor does not answer. */
|
|
75
|
+
export declare function silentSupervisorMessage(found: Extract<FoundSupervisor, {
|
|
76
|
+
status: "silent";
|
|
77
|
+
}>, env?: Env): string;
|
|
78
|
+
/**
|
|
79
|
+
* The supervisor of this OS user. A recorded one whose process has ended is
|
|
80
|
+
* none: what it held ended with it. One whose process runs and does not
|
|
81
|
+
* answer, or speaks another protocol, is `silent`: the caller says so and
|
|
82
|
+
* stops, it never supervises in its place. A supervisor installed to start
|
|
83
|
+
* at login is silent too when it is not running.
|
|
84
|
+
*/
|
|
85
|
+
export declare function findSupervisor(env?: Env): Promise<FoundSupervisor>;
|
|
86
|
+
//#endregion
|
|
87
|
+
export {};
|
|
88
|
+
//# sourceMappingURL=supervisor-record.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"supervisor-record.d.mts","names":[],"sources":["../src/supervisor-record.ts"],"mappings":";;;;;;;;;;;;;KAwBK,MAAM,SAAS;;;qBAIP;;wBAGG,eAAe,MAAK;wBAKpB,qBAAqB,MAAK;wBAI1B,mBAAmB,MAAK;;;YAM5B;qBAEC,wBAAsB,EAAA;;;;;;;;;;;;GAUjC,EAAA,KAAA;YACU,mBAAmB,EAAE,aAAa;;iBAG7B;EACf;EACA;EACA;EACA;EACA;EACA;;YAGU;;;EAEN;;EACA;EAAmB,QAAQ;EAAkB,OAAO;;;;EAEpD;EAAkB;EAAa;;;;wBAIrB,qBACd,MAAK,MACJ;;;wBAaa,mBAAmB,MAAK;;wBAiBxB,qBACd,MAAK;EACF;EAAa;;;wBAmBF,wBACd,OAAO,QAAQ;EAAmB;IAClC,MAAK;;;;;;;;wBAgBe,eACpB,MAAK,MACJ,QAAQ"}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { a as processStartedAtMs, n as isPidAlive } from "./run-record-C6oTZF_C.mjs";
|
|
2
|
+
import { callControl, controlRecordSchema, protocolMismatch } from "./control-channel.mjs";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
//#region src/supervisor-record.ts
|
|
8
|
+
/** Names another folder than `~/.ph/supervisor` (tests, a second user data
|
|
9
|
+
* root). */
|
|
10
|
+
const SUPERVISOR_HOME_ENV = "PH_SUPERVISOR_HOME";
|
|
11
|
+
/** The supervisor's folder of this OS user. */
|
|
12
|
+
function supervisorHome(env = process.env) {
|
|
13
|
+
const given = env[SUPERVISOR_HOME_ENV];
|
|
14
|
+
return path.resolve(given || path.join(os.homedir(), ".ph", "supervisor"));
|
|
15
|
+
}
|
|
16
|
+
function supervisorRecordPath(env = process.env) {
|
|
17
|
+
return path.join(supervisorHome(env), "supervisor.json");
|
|
18
|
+
}
|
|
19
|
+
function supervisorLockPath(env = process.env) {
|
|
20
|
+
return path.join(supervisorHome(env), "supervisor.lock");
|
|
21
|
+
}
|
|
22
|
+
const supervisorRecordSchema = z.object({
|
|
23
|
+
version: z.literal(1),
|
|
24
|
+
pid: z.number().int().positive(),
|
|
25
|
+
startedAt: z.string(),
|
|
26
|
+
/** The version of the package the supervisor runs from. */
|
|
27
|
+
supervisorVersion: z.string(),
|
|
28
|
+
mode: z.string(),
|
|
29
|
+
/** The OS user it runs as. */
|
|
30
|
+
user: z.string(),
|
|
31
|
+
control: controlRecordSchema
|
|
32
|
+
});
|
|
33
|
+
/** The supervisor's record as written; undefined when there is none, or it
|
|
34
|
+
* cannot be read. */
|
|
35
|
+
function readSupervisorRecord(env = process.env) {
|
|
36
|
+
try {
|
|
37
|
+
const parsed = supervisorRecordSchema.safeParse(JSON.parse(fs.readFileSync(supervisorRecordPath(env), "utf8")));
|
|
38
|
+
return parsed.success ? parsed.data : void 0;
|
|
39
|
+
} catch {
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** Whether a supervisor is recorded at all: one file read, for a tool that
|
|
44
|
+
* otherwise has nothing to ask. */
|
|
45
|
+
function supervisorRecorded(env = process.env) {
|
|
46
|
+
return fs.existsSync(supervisorRecordPath(env));
|
|
47
|
+
}
|
|
48
|
+
const START_SLACK_MS = 5e3;
|
|
49
|
+
/** Whether the process `pid` is the one that wrote at `recordedAt`. */
|
|
50
|
+
function isRecordedProcess(pid, recordedAt) {
|
|
51
|
+
if (!isPidAlive(pid)) return false;
|
|
52
|
+
const written = Date.parse(recordedAt);
|
|
53
|
+
const started = processStartedAtMs(pid);
|
|
54
|
+
if (!Number.isFinite(written) || started === void 0) return true;
|
|
55
|
+
return started <= written + START_SLACK_MS;
|
|
56
|
+
}
|
|
57
|
+
/** The process a lock file names, when it still runs. */
|
|
58
|
+
function supervisorLockHolder(env = process.env) {
|
|
59
|
+
try {
|
|
60
|
+
const lock = JSON.parse(fs.readFileSync(supervisorLockPath(env), "utf8"));
|
|
61
|
+
if (typeof lock.pid !== "number" || typeof lock.startedAt !== "string") return;
|
|
62
|
+
return isRecordedProcess(lock.pid, lock.startedAt) ? {
|
|
63
|
+
pid: lock.pid,
|
|
64
|
+
startedAt: lock.startedAt
|
|
65
|
+
} : void 0;
|
|
66
|
+
} catch {
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const HELLO_TIMEOUT_MS = 3e3;
|
|
71
|
+
/** How a tool is told that the recorded supervisor does not answer. */
|
|
72
|
+
function silentSupervisorMessage(found, env = process.env) {
|
|
73
|
+
return `A supervisor is recorded for this user (pid ${found.pid}, ${supervisorRecordPath(env)}) and does not answer: ${found.reason} Nothing was started: the same instance could then run twice. End process ${found.pid}, or delete the record if that process is no supervisor, and run this again.`;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The supervisor of this OS user. A recorded one whose process has ended is
|
|
77
|
+
* none: what it held ended with it. One whose process runs and does not
|
|
78
|
+
* answer, or speaks another protocol, is `silent`: the caller says so and
|
|
79
|
+
* stops, it never supervises in its place. A supervisor installed to start
|
|
80
|
+
* at login is silent too when it is not running.
|
|
81
|
+
*/
|
|
82
|
+
async function findSupervisor(env = process.env) {
|
|
83
|
+
if (!supervisorRecorded(env)) return { status: "none" };
|
|
84
|
+
const record = readSupervisorRecord(env);
|
|
85
|
+
if (!record) {
|
|
86
|
+
const holder = supervisorLockHolder(env);
|
|
87
|
+
return holder ? {
|
|
88
|
+
status: "silent",
|
|
89
|
+
pid: holder.pid,
|
|
90
|
+
reason: "its record cannot be read."
|
|
91
|
+
} : { status: "none" };
|
|
92
|
+
}
|
|
93
|
+
if (!isPidAlive(record.pid)) return record.mode === "installed" ? {
|
|
94
|
+
status: "silent",
|
|
95
|
+
pid: record.pid,
|
|
96
|
+
reason: "it is installed to start at login and is not running."
|
|
97
|
+
} : { status: "none" };
|
|
98
|
+
if (record.control.protocol !== 2) return {
|
|
99
|
+
status: "silent",
|
|
100
|
+
pid: record.pid,
|
|
101
|
+
reason: protocolMismatch(record.control.protocol)
|
|
102
|
+
};
|
|
103
|
+
try {
|
|
104
|
+
const hello = await callControl(record.control, "hello", void 0, { timeoutMs: HELLO_TIMEOUT_MS });
|
|
105
|
+
if (hello?.supervisor !== true) return {
|
|
106
|
+
status: "silent",
|
|
107
|
+
pid: record.pid,
|
|
108
|
+
reason: "what answers at its address is no supervisor."
|
|
109
|
+
};
|
|
110
|
+
return {
|
|
111
|
+
status: "running",
|
|
112
|
+
record,
|
|
113
|
+
hello
|
|
114
|
+
};
|
|
115
|
+
} catch (error) {
|
|
116
|
+
if (!isRecordedProcess(record.pid, record.startedAt)) return { status: "none" };
|
|
117
|
+
return {
|
|
118
|
+
status: "silent",
|
|
119
|
+
pid: record.pid,
|
|
120
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
//#endregion
|
|
125
|
+
export { SUPERVISOR_HOME_ENV, findSupervisor, readSupervisorRecord, silentSupervisorMessage, supervisorHome, supervisorLockHolder, supervisorLockPath, supervisorRecordPath, supervisorRecordSchema, supervisorRecorded };
|
|
126
|
+
|
|
127
|
+
//# sourceMappingURL=supervisor-record.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"supervisor-record.mjs","names":[],"sources":["../src/supervisor-record.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport {\n callControl,\n CONTROL_PROTOCOL,\n controlRecordSchema,\n protocolMismatch,\n} from \"./control-channel.js\";\nimport { isPidAlive, processStartedAtMs } from \"./run-record.js\";\n\n/**\n * Where the supervisor of an OS user records itself, and how a tool of that\n * user finds it without knowing a project. One folder per user:\n *\n * supervisor.json the running supervisor: its process and its control\n * channel (address and token; the user's alone)\n * supervisor.lock the process that is, or is becoming, the supervisor\n * logs/ the output of instances started without a log file\n *\n * This module reads only: it starts nothing.\n */\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\n/** Names another folder than `~/.ph/supervisor` (tests, a second user data\n * root). */\nexport const SUPERVISOR_HOME_ENV = \"PH_SUPERVISOR_HOME\";\n\n/** The supervisor's folder of this OS user. */\nexport function supervisorHome(env: Env = process.env): string {\n const given = env[SUPERVISOR_HOME_ENV];\n return path.resolve(given || path.join(os.homedir(), \".ph\", \"supervisor\"));\n}\n\nexport function supervisorRecordPath(env: Env = process.env): string {\n return path.join(supervisorHome(env), \"supervisor.json\");\n}\n\nexport function supervisorLockPath(env: Env = process.env): string {\n return path.join(supervisorHome(env), \"supervisor.lock\");\n}\n\n/** `standalone`: `ph run supervisor` in a terminal. `installed`: started at\n * login. */\nexport type SupervisorMode = \"standalone\" | \"installed\";\n\nexport const supervisorRecordSchema = z.object({\n version: z.literal(1),\n pid: z.number().int().positive(),\n startedAt: z.string(),\n /** The version of the package the supervisor runs from. */\n supervisorVersion: z.string(),\n mode: z.string(),\n /** The OS user it runs as. */\n user: z.string(),\n control: controlRecordSchema,\n});\nexport type SupervisorRecord = z.infer<typeof supervisorRecordSchema>;\n\n/** What a supervisor answers to `hello`. */\nexport interface SupervisorHello {\n supervisor: true;\n protocol: number;\n pid: number;\n mode: string;\n version: string;\n methods: string[];\n}\n\nexport type FoundSupervisor =\n /** None is recorded, or the recorded one has ended. */\n | { status: \"none\" }\n | { status: \"running\"; record: SupervisorRecord; hello: SupervisorHello }\n /** One is recorded and does not answer: nothing may be started beside it. */\n | { status: \"silent\"; pid: number; reason: string };\n\n/** The supervisor's record as written; undefined when there is none, or it\n * cannot be read. */\nexport function readSupervisorRecord(\n env: Env = process.env,\n): SupervisorRecord | undefined {\n try {\n const parsed = supervisorRecordSchema.safeParse(\n JSON.parse(fs.readFileSync(supervisorRecordPath(env), \"utf8\")),\n );\n return parsed.success ? parsed.data : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Whether a supervisor is recorded at all: one file read, for a tool that\n * otherwise has nothing to ask. */\nexport function supervisorRecorded(env: Env = process.env): boolean {\n return fs.existsSync(supervisorRecordPath(env));\n}\n\n// A record is written by the process it names: see run-record.ts.\nconst START_SLACK_MS = 5_000;\n\n/** Whether the process `pid` is the one that wrote at `recordedAt`. */\nfunction isRecordedProcess(pid: number, recordedAt: string): boolean {\n if (!isPidAlive(pid)) return false;\n const written = Date.parse(recordedAt);\n const started = processStartedAtMs(pid);\n if (!Number.isFinite(written) || started === undefined) return true;\n return started <= written + START_SLACK_MS;\n}\n\n/** The process a lock file names, when it still runs. */\nexport function supervisorLockHolder(\n env: Env = process.env,\n): { pid: number; startedAt: string } | undefined {\n try {\n const lock = JSON.parse(\n fs.readFileSync(supervisorLockPath(env), \"utf8\"),\n ) as { pid?: unknown; startedAt?: unknown };\n if (typeof lock.pid !== \"number\" || typeof lock.startedAt !== \"string\") {\n return undefined;\n }\n return isRecordedProcess(lock.pid, lock.startedAt)\n ? { pid: lock.pid, startedAt: lock.startedAt }\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nconst HELLO_TIMEOUT_MS = 3_000;\n\n/** How a tool is told that the recorded supervisor does not answer. */\nexport function silentSupervisorMessage(\n found: Extract<FoundSupervisor, { status: \"silent\" }>,\n env: Env = process.env,\n): string {\n return (\n `A supervisor is recorded for this user (pid ${found.pid}, ${supervisorRecordPath(env)}) and does not answer: ${found.reason} ` +\n \"Nothing was started: the same instance could then run twice. \" +\n `End process ${found.pid}, or delete the record if that process is no supervisor, and run this again.`\n );\n}\n\n/**\n * The supervisor of this OS user. A recorded one whose process has ended is\n * none: what it held ended with it. One whose process runs and does not\n * answer, or speaks another protocol, is `silent`: the caller says so and\n * stops, it never supervises in its place. A supervisor installed to start\n * at login is silent too when it is not running.\n */\nexport async function findSupervisor(\n env: Env = process.env,\n): Promise<FoundSupervisor> {\n if (!supervisorRecorded(env)) return { status: \"none\" };\n const record = readSupervisorRecord(env);\n if (!record) {\n // Unreadable: only the lock says whether one runs.\n const holder = supervisorLockHolder(env);\n return holder\n ? {\n status: \"silent\",\n pid: holder.pid,\n reason: \"its record cannot be read.\",\n }\n : { status: \"none\" };\n }\n if (!isPidAlive(record.pid)) {\n return record.mode === \"installed\"\n ? {\n status: \"silent\",\n pid: record.pid,\n reason: \"it is installed to start at login and is not running.\",\n }\n : { status: \"none\" };\n }\n if (record.control.protocol !== CONTROL_PROTOCOL) {\n return {\n status: \"silent\",\n pid: record.pid,\n reason: protocolMismatch(record.control.protocol),\n };\n }\n try {\n const hello = (await callControl(record.control, \"hello\", undefined, {\n timeoutMs: HELLO_TIMEOUT_MS,\n })) as Partial<SupervisorHello> | null;\n if (hello?.supervisor !== true) {\n return {\n status: \"silent\",\n pid: record.pid,\n reason: \"what answers at its address is no supervisor.\",\n };\n }\n return { status: \"running\", record, hello: hello as SupervisorHello };\n } catch (error) {\n // The pid may have gone to another process since.\n if (!isRecordedProcess(record.pid, record.startedAt)) {\n return { status: \"none\" };\n }\n return {\n status: \"silent\",\n pid: record.pid,\n reason: error instanceof Error ? error.message : String(error),\n };\n }\n}\n"],"mappings":";;;;;;;;;AA4BA,MAAa,sBAAsB;;AAGnC,SAAgB,eAAe,MAAW,QAAQ,KAAa;CAC7D,MAAM,QAAQ,IAAI;CAClB,OAAO,KAAK,QAAQ,SAAS,KAAK,KAAK,GAAG,QAAQ,GAAG,OAAO,YAAY,CAAC;AAC3E;AAEA,SAAgB,qBAAqB,MAAW,QAAQ,KAAa;CACnE,OAAO,KAAK,KAAK,eAAe,GAAG,GAAG,iBAAiB;AACzD;AAEA,SAAgB,mBAAmB,MAAW,QAAQ,KAAa;CACjE,OAAO,KAAK,KAAK,eAAe,GAAG,GAAG,iBAAiB;AACzD;AAMA,MAAa,yBAAyB,EAAE,OAAO;CAC7C,SAAS,EAAE,QAAQ,CAAC;CACpB,KAAK,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS;CAC/B,WAAW,EAAE,OAAO;;CAEpB,mBAAmB,EAAE,OAAO;C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