@powerhousedao/switchboard 6.2.3-dev.74 → 6.2.3-dev.76

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-CJjK7WpR.mjs","sources":["../src/pglite-version.ts","../src/profiler.ts","../src/attachments/auth.ts","../src/attachments/mount-auth.ts","../src/attachments/routes.ts","../src/attachments/url-signer.ts","../src/attachments/index.ts","../src/attachment-reference-read-model.mts","../src/builder-defaults.mts","../src/plugins/attachments.mts","../src/plugin-host.mts","../src/inspection-throttle.mts","../src/feature-flags.ts","../src/inspection-flag.mts","../src/mcp-flag.mts","../src/pglite-dialect.ts","../src/pglite-migration.ts","../src/pglite-preflight.ts","../src/pglite-store.mts","../src/create-signature-policy.mts","../src/renown.ts","../src/unsupported-stored-documents.mts","../src/store-lock.mts","../src/server.mts"],"sourcesContent":["import type * as CurrentPGliteModuleNs from \"@electric-sql/pglite\";\nimport type {\n NodeFsClass,\n PGliteModuleSpec,\n VerifyHandle,\n} from \"@powerhousedao/reactor-api/pglite-node\";\nimport { promises as fs } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nexport const CURRENT_PG_MAJOR = 17;\nexport const SUPPORTED_PG_MAJORS = [16, 17] as const;\nexport type SupportedPgMajor = (typeof SUPPORTED_PG_MAJORS)[number];\n\ntype CurrentPGliteModule = typeof CurrentPGliteModuleNs;\n\nexport async function readPgVersionFile(\n dataDir: string,\n): Promise<number | null> {\n try {\n const raw = await fs.readFile(path.join(dataDir, \"PG_VERSION\"), \"utf8\");\n const major = parseInt(raw.trim(), 10);\n return Number.isFinite(major) ? major : null;\n } catch {\n return null;\n }\n}\n\nexport function isSupportedMajor(major: number): major is SupportedPgMajor {\n return (SUPPORTED_PG_MAJORS as readonly number[]).includes(major);\n}\n\n/**\n * Parses the `PH_FORCE_PG_VERSION` env var. Returns the validated major, or\n * `null` when the var is unset/empty. Throws on any value that is not a\n * supported major — invalid configuration must fail before the server starts\n * touching disk.\n */\nexport function parseForcePgVersion(\n raw: string | undefined,\n): SupportedPgMajor | null {\n if (raw === undefined || raw.trim() === \"\") return null;\n const parsed = Number(raw);\n if (Number.isInteger(parsed) && isSupportedMajor(parsed)) return parsed;\n throw new Error(\n `PH_FORCE_PG_VERSION must be one of: ${SUPPORTED_PG_MAJORS.join(\", \")} (got: ${raw})`,\n );\n}\n\nexport async function loadPGliteModule(\n major: SupportedPgMajor,\n): Promise<CurrentPGliteModule> {\n if (major === 16) {\n return (await import(\"pglite-legacy-02\")) as unknown as CurrentPGliteModule;\n }\n return import(\"@electric-sql/pglite\");\n}\n\n/**\n * Where a PGlite worker imports the module that opens `major` dirs from,\n * resolved here because the worker's own package cannot see the\n * `pglite-legacy-02` alias.\n */\nexport function pgliteModuleSpec(major: SupportedPgMajor): PGliteModuleSpec {\n const base = major === 16 ? \"pglite-legacy-02\" : \"@electric-sql/pglite\";\n return {\n pglite: resolveModuleUrl(base),\n nodefs: resolveModuleUrl(`${base}/nodefs`),\n };\n}\n\nfunction resolveModuleUrl(specifier: string): string {\n try {\n return import.meta.resolve(specifier);\n } catch {\n return pathToFileURL(createRequire(import.meta.url).resolve(specifier))\n .href;\n }\n}\n\n/** The stock NodeFS class of the PGlite module that opens `major` dirs. */\nexport async function loadNodeFsClass(\n major: SupportedPgMajor,\n): Promise<NodeFsClass> {\n if (major === 16) {\n const mod = await import(\"pglite-legacy-02/nodefs\");\n return mod.NodeFS as unknown as NodeFsClass;\n }\n const mod = await import(\"@electric-sql/pglite/nodefs\");\n return mod.NodeFS;\n}\n\n/** Opens a converted dir over stock NodeFS so the conversion can check it. */\nexport async function openForVerify(\n major: number,\n dataDir: string,\n): Promise<VerifyHandle> {\n if (!isSupportedMajor(major)) {\n throw new Error(\n `Cannot verify PGlite data dir ${dataDir}: PG_VERSION=${major} is not supported (expected one of ${SUPPORTED_PG_MAJORS.join(\", \")})`,\n );\n }\n const [{ PGlite }, NodeFS] = await Promise.all([\n loadPGliteModule(major),\n loadNodeFsClass(major),\n ]);\n const pg = new PGlite({ fs: new NodeFS(dataDir) });\n await pg.waitReady;\n return pg;\n}\n\ntype PgDumpFn = (options: {\n pg: unknown;\n}) => Promise<{ text(): Promise<string> }>;\n\nexport async function loadPgDump(major: SupportedPgMajor): Promise<PgDumpFn> {\n if (major === 16) {\n const mod = (await import(\"pglite-tools-legacy-02/pg_dump\")) as {\n pgDump: PgDumpFn;\n };\n return mod.pgDump;\n }\n const mod = (await import(\"@electric-sql/pglite-tools/pg_dump\")) as {\n pgDump: PgDumpFn;\n };\n return mod.pgDump;\n}\n","import type { PyroscopeConfig } from \"@pyroscope/nodejs\";\n\nlet started = false;\n\n// Once per process: the standalone entry and an embedding host (ph vetra) both\n// ask, and Pyroscope must only be initialised once.\nexport async function initProfilerFromEnv(env: typeof process.env) {\n if (started || !env.PYROSCOPE_SERVER_ADDRESS) return;\n started = true;\n const {\n PYROSCOPE_SERVER_ADDRESS: serverAddress,\n PYROSCOPE_APPLICATION_NAME: appName,\n PYROSCOPE_USER: basicAuthUser,\n PYROSCOPE_PASSWORD: basicAuthPassword,\n PYROSCOPE_WALL_ENABLED: wallEnabled,\n PYROSCOPE_HEAP_ENABLED: heapEnabled,\n } = env;\n\n const options: PyroscopeConfig = {\n serverAddress,\n appName,\n basicAuthUser,\n basicAuthPassword,\n // Wall profiling captures wall-clock time (includes async I/O waits)\n // This shows GraphQL resolvers even when waiting for database\n wall: {\n samplingDurationMs: 10000, // 10 second sampling windows\n samplingIntervalMicros: 10000, // 10ms sampling interval (100 samples/sec)\n collectCpuTime: true, // Also collect CPU time alongside wall time\n },\n // Heap profiling for memory allocation tracking\n heap: {\n samplingIntervalBytes: 512 * 1024, // Sample every 512KB allocated\n stackDepth: 64, // Capture deeper stacks for better context\n },\n };\n return initProfiler(options, {\n wallEnabled: wallEnabled !== \"false\",\n heapEnabled: heapEnabled === \"true\",\n });\n}\n\ninterface ProfilerFlags {\n wallEnabled?: boolean;\n heapEnabled?: boolean;\n}\n\nexport async function initProfiler(\n options?: PyroscopeConfig,\n flags: ProfilerFlags = { wallEnabled: true, heapEnabled: false },\n) {\n console.log(\"Initializing Pyroscope profiler at:\", options?.serverAddress);\n console.log(\" Wall profiling:\", flags.wallEnabled ? \"enabled\" : \"disabled\");\n console.log(\" Heap profiling:\", flags.heapEnabled ? \"enabled\" : \"disabled\");\n\n const { default: Pyroscope } = await import(\"@pyroscope/nodejs\");\n Pyroscope.init(options);\n\n // Start wall profiling (captures async I/O time - shows resolvers)\n if (flags.wallEnabled) {\n Pyroscope.startWallProfiling();\n }\n\n // Start CPU profiling (captures CPU-bound work)\n Pyroscope.startCpuProfiling();\n\n // Optionally start heap profiling (memory allocations)\n if (flags.heapEnabled) {\n Pyroscope.startHeapProfiling();\n }\n}\n","import type { AuthContext, AuthService } from \"@powerhousedao/reactor-api\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\n/**\n * Verified actor context for authenticated attachment handlers. The user comes\n * exclusively from bearer verification: when auth is disabled (OPEN mode)\n * `user` is undefined and `authEnabled` is false, and handlers must treat the\n * caller as anonymous. Caller-supplied identity headers are never consulted.\n */\nexport type AttachmentActorContext = {\n user: AuthContext[\"user\"];\n authEnabled: boolean;\n};\n\nconst ANONYMOUS_ACTOR: AttachmentActorContext = {\n user: undefined,\n authEnabled: false,\n};\n\nexport type NodeHandler = (\n req: IncomingMessage,\n res: ServerResponse,\n body?: unknown,\n actor?: AttachmentActorContext,\n) => Promise<void> | void;\n\nexport type RequireAuthOptions = {\n /**\n * Let requests without a bearer identity through as anonymous actors\n * instead of answering 401, so the handler's own document authorization\n * decides. A bearer that IS supplied must still verify — an invalid token\n * is rejected, never downgraded to anonymous.\n */\n allowAnonymous?: boolean;\n /**\n * Whether the deployment has said it accepts no anonymous callers at all\n * (`REQUIRE_AUTHENTICATED_CALLER`). It overrides `allowAnonymous`, because\n * the two answer different questions: `allowAnonymous` says \"this handler\n * authorizes per document, so it does not need identity to decide\", while\n * this says \"this server does not serve callers it cannot name\". A route can\n * be happy to decide without identity and still not be allowed to.\n *\n * These routes are mounted straight on the HTTP adapter, so the fetch chain's\n * own require-auth middleware never sees them — this is how the same floor\n * reaches them.\n */\n requireAuthenticatedCaller?: boolean;\n};\n\n/**\n * Wrap a Node-style handler so that, when `authService` is provided and auth is\n * enabled, the request must carry a verifiable Bearer token. The handler always\n * receives an actor context: the verified bearer user when auth is enabled, or\n * the anonymous context when it is disabled. With `allowAnonymous`, a missing\n * bearer yields an anonymous actor with `authEnabled: true` instead of a 401 —\n * unless `requireAuthenticatedCaller` says the deployment refuses anonymous\n * callers outright, which overrides it.\n *\n * With no `authService` there is no bearer to read and every caller is\n * anonymous, so nothing is refused here. That combination cannot carry the\n * floor: `assertRequireAuthenticatedCallerAllowed` refuses to boot with\n * `REQUIRE_AUTHENTICATED_CALLER` set and no identity resolution, and identity\n * resolution is what builds the service.\n */\nexport function requireAuth(\n authService: AuthService | undefined,\n handler: NodeHandler,\n options?: RequireAuthOptions,\n): NodeHandler {\n if (!authService) {\n return (req, res, body) => handler(req, res, body, ANONYMOUS_ACTOR);\n }\n\n return async (req, res, body) => {\n let result;\n try {\n result = await authService.verifyBearer(req.headers.authorization);\n } catch {\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify({ error: \"Internal authentication error\" }));\n return;\n }\n\n if (result instanceof Response) {\n const body = await result.text();\n res.statusCode = result.status;\n const contentType = result.headers.get(\"content-type\");\n if (contentType) res.setHeader(\"Content-Type\", contentType);\n res.end(body);\n return;\n }\n\n if (!result.user) {\n const refuse =\n options?.requireAuthenticatedCaller === true ||\n (result.auth_enabled && !options?.allowAnonymous);\n if (refuse) {\n res.statusCode = 401;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify({ error: \"Authentication required\" }));\n return;\n }\n }\n\n await handler(req, res, body, {\n user: result.user,\n authEnabled: result.auth_enabled,\n });\n };\n}\n","import type { API } from \"@powerhousedao/reactor-api\";\nimport {\n requireAuth,\n type NodeHandler,\n type RequireAuthOptions,\n} from \"./auth.js\";\n\nexport type HttpMethod = \"DELETE\" | \"GET\" | \"HEAD\" | \"POST\" | \"PUT\";\n\n// rawBody dispatches ahead of every body parser, so the handler streams `req`.\ntype MountOptions = Pick<\n NonNullable<Parameters<API[\"httpAdapter\"][\"mountNodeRoute\"]>[3]>,\n \"rawBody\"\n>;\n\n/**\n * Mount a Node-style attachment route with `requireAuth` applied unconditionally.\n * When `api.authService` is undefined (auth disabled), the handler still runs\n * through `requireAuth` and receives the anonymous actor context — that is the\n * only way to opt out of bearer verification. To register a route without auth\n * wrapping you must call `api.httpAdapter.mountNodeRoute` directly.\n *\n * `allowAnonymous` is reserved for routes whose handlers make a per-document\n * authorization decision themselves; identity-only routes must not use it. It\n * is also not the last word: a deployment that refuses anonymous callers\n * (`REQUIRE_AUTHENTICATED_CALLER`) refuses them here too, because these routes\n * are mounted on the HTTP adapter and never reach the fetch chain that carries\n * that floor for GraphQL. The flag is read from the API, so every route\n * mounted through here inherits it without each one remembering to.\n */\nexport function mountAuthenticatedNodeRoute(\n api: Pick<API, \"httpAdapter\" | \"authService\" | \"requireAuthenticatedCaller\">,\n method: HttpMethod,\n path: string,\n handler: NodeHandler,\n options?: RequireAuthOptions & MountOptions,\n): void {\n const { rawBody, ...authOptions } = options ?? {};\n api.httpAdapter.mountNodeRoute(\n method,\n path,\n requireAuth(api.authService, handler, {\n ...authOptions,\n requireAuthenticatedCaller: api.requireAuthenticatedCaller,\n }),\n { rawBody: rawBody ?? false },\n );\n}\n","import {\n AttachmentAlreadyExists,\n AttachmentNotFound,\n AttachmentPending,\n HashMismatch,\n InvalidAttachmentMetadata,\n InvalidAttachmentRef,\n ReservationNotFound,\n SizeMismatch,\n UploadTooLarge,\n createRef,\n parseAttachmentDownloadTarget,\n validateReserveMetadata,\n type AttachmentBuildResult,\n type AttachmentDownloadTarget,\n type ReserveAttachmentOptions,\n type ReserveMetadata,\n} from \"@powerhousedao/reactor-attachments\";\nimport type { IAttachmentAccessService } from \"@powerhousedao/reactor-api\";\nimport type { AttachmentHash } from \"@powerhousedao/reactor\";\nimport { childLogger } from \"document-model\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport type { ReadableStream as NodeReadableStream } from \"node:stream/web\";\nimport type { AttachmentActorContext } from \"./auth.js\";\nimport type { AttachmentUrlSigner } from \"./url-signer.js\";\n\nconst logger = childLogger([\"switchboard\", \"attachments\"]);\n\nconst RETRY_AFTER_SECONDS = 5;\n\n// Canonical form is lowercase hex (the SHA-256 hasher emits lowercase), but\n// accept either case from the wire and normalise before lookup. This keeps\n// the API forgiving for hand-typed URLs without changing storage semantics.\nconst HASH_PATTERN = /^[a-f0-9]{64}$/i;\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.statusCode = status;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify(body));\n}\n\nfunction sendError(res: ServerResponse, status: number, message: string): void {\n sendJson(res, status, { error: message });\n}\n\nfunction statusForError(err: unknown): number {\n if (err instanceof AttachmentNotFound) return 404;\n if (err instanceof ReservationNotFound) return 404;\n if (err instanceof InvalidAttachmentRef) return 400;\n if (err instanceof UploadTooLarge) return 413;\n return 500;\n}\n\nfunction sendErrorFromException(res: ServerResponse, err: unknown): void {\n const status = statusForError(err);\n if (status >= 500) {\n logger.error(\"Attachment route error: @error\", err);\n sendError(res, status, \"Internal error\");\n return;\n }\n sendError(res, status, err instanceof Error ? err.message : String(err));\n}\n\nasync function readJsonBody(\n req: IncomingMessage,\n body: unknown,\n): Promise<unknown> {\n // The Express body-parser may have already populated `body`. When that\n // happens we trust it; otherwise read the raw stream ourselves so this\n // module is independent of upstream middleware ordering.\n if (body !== undefined && body !== null && typeof body === \"object\") {\n return body;\n }\n const chunks: Buffer[] = [];\n for await (const chunk of req) {\n chunks.push(chunk as Buffer);\n }\n if (chunks.length === 0) return undefined;\n const text = Buffer.concat(chunks).toString(\"utf8\");\n if (text.length === 0) return undefined;\n return JSON.parse(text);\n}\n\nexport function parseReserveOptions(\n input: unknown,\n): ReserveAttachmentOptions | null {\n if (input === null || typeof input !== \"object\") return null;\n const obj = input as Record<string, unknown>;\n const { mimeType, fileName } = obj;\n const extension = obj.extension ?? null;\n try {\n validateReserveMetadata({\n mimeType,\n fileName,\n extension,\n } as ReserveMetadata);\n } catch (err) {\n if (err instanceof InvalidAttachmentMetadata) return null;\n throw err;\n }\n if (typeof mimeType !== \"string\" || typeof fileName !== \"string\") return null;\n if (extension !== null && typeof extension !== \"string\") return null;\n\n // Hash-first mode: clientHash triggers this path; sizeBytes is required alongside it.\n // A body with sizeBytes but no clientHash falls through to the legacy path unchanged.\n if (obj.clientHash !== undefined) {\n if (\n typeof obj.clientHash !== \"string\" ||\n !HASH_PATTERN.test(obj.clientHash)\n ) {\n return null;\n }\n // Zero is accepted: an empty file is a real upload. The hash-first check\n // still binds the bytes received to the declared hash and size, so a\n // drained body cannot pass as an empty file unless one was declared.\n if (\n typeof obj.sizeBytes !== \"number\" ||\n !Number.isSafeInteger(obj.sizeBytes) ||\n obj.sizeBytes < 0\n ) {\n return null;\n }\n return {\n mimeType,\n fileName,\n extension,\n clientHash: obj.clientHash.toLowerCase() as AttachmentHash,\n sizeBytes: obj.sizeBytes,\n };\n }\n\n return {\n mimeType,\n fileName,\n extension,\n };\n}\n\nexport function quoteFilename(name: string): string {\n // RFC 6266: quoted-string with internal \" and \\ escaped.\n return `\"${name.replace(/[\\\\\"]/g, \"\\\\$&\")}\"`;\n}\n\nexport function buildContentDisposition(fileName: string): string {\n // ASCII fallback: replace any byte outside printable ASCII (0x20-0x7e),\n // plus `\"` and `\\`, with `_`. Browsers fall back to this when they don't\n // grok `filename*=`; the modern parameter carries the real name.\n const ascii = fileName.replace(/[^\\x20-\\x21\\x23-\\x5b\\x5d-\\x7e]/g, \"_\");\n // RFC 5987: percent-encode UTF-8 bytes. encodeURIComponent leaves a few\n // chars that 5987 disallows in token; re-encode them.\n const encoded = encodeURIComponent(fileName).replace(\n /['()*!]/g,\n (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n );\n return `attachment; filename=${quoteFilename(ascii)}; filename*=UTF-8''${encoded}`;\n}\n\nexport function makeReserveHandler(attachments: AttachmentBuildResult) {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n body?: unknown,\n ): Promise<void> => {\n let parsed: unknown;\n try {\n parsed = await readJsonBody(req, body);\n } catch {\n sendError(res, 400, \"Invalid JSON body\");\n return;\n }\n const opts = parseReserveOptions(parsed);\n if (!opts) {\n sendError(\n res,\n 400,\n \"Body must be { mimeType: string (type/subtype), fileName: string (no control characters, max 255 chars), extension?: string|null, clientHash?: string (64 hex chars), sizeBytes?: number (required with clientHash) }\",\n );\n return;\n }\n\n let upload;\n try {\n upload = await attachments.service.reserve(opts);\n } catch (err) {\n if (err instanceof AttachmentAlreadyExists) {\n sendJson(res, 409, { error: \"already_exists\", ref: err.ref });\n return;\n }\n sendErrorFromException(res, err);\n return;\n }\n\n sendJson(res, 201, {\n reservationId: upload.reservationId,\n ref: upload.ref,\n expiresAtUtc: upload.expiresAtUtc,\n ...(upload.uploadTarget ? { uploadTarget: upload.uploadTarget } : {}),\n });\n };\n}\n\nexport function makeUploadHandler(attachments: AttachmentBuildResult) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const reservationId = extractParam(req, \"reservationId\");\n if (!reservationId) {\n sendError(res, 400, \"Missing reservationId\");\n return;\n }\n if (attachments.backend?.kind === \"s3\") {\n sendError(res, 405, \"Use the reservation uploadTarget for S3 uploads\");\n return;\n }\n\n let reservation;\n try {\n reservation = await attachments.reservations.get(reservationId);\n } catch (err) {\n sendErrorFromException(res, err);\n return;\n }\n\n const upload = attachments.uploadFactory.createUpload(reservation);\n\n const webStream = Readable.toWeb(\n req as Readable,\n ) as ReadableStream<Uint8Array>;\n\n try {\n const result = await upload.send(webStream);\n sendJson(res, 200, result);\n } catch (err) {\n if (err instanceof HashMismatch) {\n sendJson(res, 422, {\n error: \"hash_mismatch\",\n claimed: err.claimed,\n actual: err.actual,\n });\n return;\n }\n if (err instanceof SizeMismatch) {\n sendJson(res, 422, {\n error: \"size_mismatch\",\n declared: err.declared,\n actual: err.actual,\n });\n return;\n }\n sendErrorFromException(res, err);\n }\n };\n}\n\nexport function makeDownloadHandler(\n attachments: AttachmentBuildResult,\n attachmentAccess: IAttachmentAccessService,\n urlSigner: AttachmentUrlSigner | null,\n) {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n _body?: unknown,\n actor?: AttachmentActorContext,\n ): Promise<void> => {\n const hash = extractParam(req, \"hash\");\n if (!hash || !HASH_PATTERN.test(hash)) {\n sendError(res, 400, \"Invalid attachment hash\");\n return;\n }\n\n const canonicalHash = hash.toLowerCase() as AttachmentHash;\n const grant = await resolveByteGrant(\n req,\n canonicalHash,\n actor,\n attachmentAccess,\n urlSigner,\n );\n if (!admitGrant(res, grant)) return;\n\n const controller = new AbortController();\n req.once(\"close\", () => controller.abort());\n\n let response;\n try {\n response = await attachments.store.get(\n canonicalHash,\n controller.signal,\n grant.documentId,\n );\n } catch (err) {\n if (err instanceof AttachmentPending) {\n res.statusCode = 202;\n res.setHeader(\"Cache-Control\", \"private\");\n res.setHeader(\"Retry-After\", String(RETRY_AFTER_SECONDS));\n res.setHeader(\n \"Attachment-Pending\",\n buildPendingHeader({\n expiresAtUtc: err.expiresAtUtc,\n ...(err.metadata ?? {}),\n }),\n );\n res.end();\n return;\n }\n sendErrorFromException(res, err);\n return;\n }\n\n const { header, body } = response;\n res.statusCode = 200;\n res.setHeader(\"Cache-Control\", \"private\");\n res.setHeader(\"Content-Type\", header.mimeType);\n res.setHeader(\"Content-Length\", String(header.sizeBytes));\n res.setHeader(\n \"Content-Disposition\",\n buildContentDisposition(header.fileName),\n );\n res.setHeader(\"Attachment-Metadata\", buildMetadataHeader(header));\n\n const source = Readable.fromWeb(\n body as unknown as NodeReadableStream<Uint8Array>,\n );\n // The blob is opened lazily, so a file missing from disk (metadata still\n // says \"available\", e.g. a pod-local store lost on restart) surfaces here\n // as a stream error. `.pipe()` does not forward it: without a listener it\n // is an unhandled 'error' event and takes the whole process down.\n source.once(\"error\", (err) => handleDownloadStreamError(res, hash, err));\n source.pipe(res);\n };\n}\n\nfunction handleDownloadStreamError(\n res: ServerResponse,\n hash: string,\n err: unknown,\n): void {\n if (res.headersSent) {\n // Bytes are already on the wire; finishing normally would hand the client\n // a truncated file as if it were complete. Cut the connection instead —\n // without passing the error, which would re-emit it on the response.\n logger.error(\"Attachment stream failed mid-download: @error\", err);\n res.destroy();\n return;\n }\n // Nothing sent yet: drop the download headers so they cannot describe the\n // JSON error body, then answer like any other missing attachment.\n res.removeHeader(\"Content-Length\");\n res.removeHeader(\"Content-Disposition\");\n res.removeHeader(\"Attachment-Metadata\");\n if ((err as NodeJS.ErrnoException | undefined)?.code === \"ENOENT\") {\n logger.warn(\n \"Attachment @hash is recorded as available but its blob is missing\",\n hash,\n );\n sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);\n return;\n }\n logger.error(\"Attachment stream failed before sending: @error\", err);\n sendError(res, 500, \"Internal error\");\n}\n\n// Node rejects header values above U+00FF. Escaping everything outside\n// printable ASCII keeps the header valid; JSON.parse restores the original.\nfunction toAsciiJson(value: unknown): string {\n return JSON.stringify(value).replace(\n /[\\u007f-\\uffff]/g,\n (char) => `\\\\u${char.charCodeAt(0).toString(16).padStart(4, \"0\")}`,\n );\n}\n\nexport function buildPendingHeader(pending: {\n expiresAtUtc: string | null;\n mimeType?: string;\n fileName?: string;\n sizeBytes?: number;\n}): string {\n return toAsciiJson(pending);\n}\n\nexport function buildMetadataHeader(header: {\n mimeType: string;\n fileName: string;\n sizeBytes: number;\n extension: string | null;\n createdAtUtc: string;\n lastAccessedAtUtc: string;\n}): string {\n return toAsciiJson({\n mimeType: header.mimeType,\n fileName: header.fileName,\n sizeBytes: header.sizeBytes,\n extension: header.extension,\n createdAtUtc: header.createdAtUtc,\n lastAccessedAtUtc: header.lastAccessedAtUtc,\n });\n}\n\nexport function makeStatHandler(\n attachments: AttachmentBuildResult,\n attachmentAccess: IAttachmentAccessService,\n urlSigner: AttachmentUrlSigner | null,\n) {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n _body?: unknown,\n actor?: AttachmentActorContext,\n ): Promise<void> => {\n const hash = extractParam(req, \"hash\");\n if (!hash || !HASH_PATTERN.test(hash)) {\n sendError(res, 400, \"Invalid attachment hash\");\n return;\n }\n\n const canonicalHash = hash.toLowerCase() as AttachmentHash;\n const grant = await resolveByteGrant(\n req,\n canonicalHash,\n actor,\n attachmentAccess,\n urlSigner,\n );\n if (!admitGrant(res, grant)) return;\n\n let header;\n try {\n header = await attachments.store.stat(canonicalHash);\n } catch (err) {\n sendErrorFromException(res, err);\n return;\n }\n\n res.setHeader(\"Cache-Control\", \"private\");\n if (header.status === \"pending\") {\n res.statusCode = 202;\n res.setHeader(\"Retry-After\", String(RETRY_AFTER_SECONDS));\n res.setHeader(\n \"Attachment-Pending\",\n buildPendingHeader({\n expiresAtUtc: header.expiresAtUtc,\n mimeType: header.mimeType,\n fileName: header.fileName,\n sizeBytes: header.sizeBytes,\n }),\n );\n res.end();\n return;\n }\n\n res.statusCode = 200;\n res.setHeader(\"Content-Type\", header.mimeType);\n res.setHeader(\"Content-Length\", String(header.sizeBytes));\n res.setHeader(\n \"Content-Disposition\",\n buildContentDisposition(header.fileName),\n );\n res.setHeader(\"Attachment-Metadata\", buildMetadataHeader(header));\n res.end();\n };\n}\n\nexport function makeGetReservationHandler(attachments: AttachmentBuildResult) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const reservationId = extractParam(req, \"reservationId\");\n if (!reservationId) {\n sendError(res, 400, \"Missing reservationId\");\n return;\n }\n try {\n const reservation = await attachments.reservations.get(reservationId);\n sendJson(res, 200, reservation);\n } catch (err) {\n sendErrorFromException(res, err);\n }\n };\n}\n\nexport function makeDeleteReservationHandler(\n attachments: AttachmentBuildResult,\n) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const reservationId = extractParam(req, \"reservationId\");\n if (!reservationId) {\n sendError(res, 400, \"Missing reservationId\");\n return;\n }\n try {\n await attachments.reservations.delete(reservationId);\n res.statusCode = 204;\n res.end();\n } catch (err) {\n sendErrorFromException(res, err);\n }\n };\n}\n\nfunction extractParam(req: IncomingMessage, name: string): string | undefined {\n const expressParams = (\n req as IncomingMessage & {\n params?: Record<string, string>;\n }\n ).params;\n return expressParams?.[name];\n}\n\nconst MAX_DOCUMENT_ID_LEN = 512;\nconst ATTACHMENT_NOT_FOUND_BODY = { error: \"Attachment not found\" };\n// SigV4 presigned URLs cannot outlive 7 days; requests above the cap are\n// clamped rather than rejected so clients need not know the ceiling.\nconst MAX_DOWNLOAD_TARGET_TTL_SECONDS = 7 * 24 * 60 * 60;\n\n/**\n * How long a download target may live, by default.\n *\n * The authorization behind a presigned URL is decided once, when it is issued,\n * and the URL keeps working until it expires however the document's policy\n * changes in between. A week of that is a revocation that does not revoke: an\n * account deactivated, a company reassigned or a group left, and the bytes stay\n * fetchable by anyone holding the link. Minutes are enough to open a file;\n * days are only enough to lose control of it.\n *\n * A deployment that needs longer sets ATTACHMENT_DOWNLOAD_TARGET_MAX_TTL_SECONDS,\n * still bounded by the signing ceiling above.\n */\nconst DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS = 300;\n\n/**\n * The ceiling in force, read per call so a deployment can set it without the\n * value being frozen at import — which is also what lets a test cover it.\n * Anything unparseable falls back to the default rather than to the maximum:\n * a typo must not quietly widen the window it was meant to narrow.\n */\nfunction downloadTargetTtlCapSeconds(): number {\n const configured = process.env.ATTACHMENT_DOWNLOAD_TARGET_MAX_TTL_SECONDS;\n if (configured === undefined) return DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS;\n const parsed = Number(configured);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n logger.warn(\n `Ignoring invalid ATTACHMENT_DOWNLOAD_TARGET_MAX_TTL_SECONDS=\"${configured}\" (expected a positive integer number of seconds) — using ${DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS}`,\n );\n return DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS;\n }\n return Math.min(parsed, MAX_DOWNLOAD_TARGET_TTL_SECONDS);\n}\n\n/**\n * Returns the single `documentId` query value, or null when it is missing,\n * duplicated, blank, or oversized. Validation happens before authorization so\n * malformed requests never reach the access service.\n */\nfunction extractSingleDocumentId(req: IncomingMessage): string | null {\n if (!req.url) return null;\n let url: URL;\n try {\n url = new URL(req.url, \"http://switchboard.invalid\");\n } catch {\n return null;\n }\n const values = url.searchParams.getAll(\"documentId\");\n if (values.length !== 1) return null;\n const value = values[0];\n if (value.trim().length === 0 || value.length > MAX_DOCUMENT_ID_LEN) {\n return null;\n }\n return value;\n}\n\n/**\n * Returns the target TTL in seconds, or \"invalid\" when the caller's own value\n * is malformed (duplicated, non-integer, or non-positive).\n *\n * The cap applies whether or not the caller asked for a lifetime: omitting\n * `expiresIn` used to fall through to whatever the storage backend was\n * configured with, which would make the ceiling something a client opts out of\n * by saying nothing.\n */\nfunction extractExpiresIn(req: IncomingMessage): number | \"invalid\" {\n const cap = downloadTargetTtlCapSeconds();\n if (!req.url) return cap;\n let url: URL;\n try {\n url = new URL(req.url, \"http://switchboard.invalid\");\n } catch {\n return cap;\n }\n const values = url.searchParams.getAll(\"expiresIn\");\n if (values.length === 0) return cap;\n if (values.length > 1) return \"invalid\";\n const parsed = Number(values[0]);\n if (!Number.isInteger(parsed) || parsed <= 0) return \"invalid\";\n return Math.min(parsed, cap);\n}\n\ntype ByteGrant =\n | { kind: \"granted\"; documentId: string }\n | { kind: \"denied\" }\n | { kind: \"unavailable\" }\n | { kind: \"error\" };\n\nfunction singleQueryValue(\n params: URLSearchParams,\n name: string,\n): string | null {\n const values = params.getAll(name);\n return values.length === 1 ? values[0] : null;\n}\n\n/**\n * Byte routes serve only under a grant: a signed URL minted by the\n * download-target route, or a documentId the caller may read the attachment\n * through. A signed request is judged by its signature alone.\n */\nasync function resolveByteGrant(\n req: IncomingMessage,\n hash: AttachmentHash,\n actor: AttachmentActorContext | undefined,\n attachmentAccess: IAttachmentAccessService,\n urlSigner: AttachmentUrlSigner | null,\n): Promise<ByteGrant> {\n let params: URLSearchParams;\n try {\n params = new URL(req.url ?? \"\", \"http://switchboard.invalid\").searchParams;\n } catch {\n return { kind: \"denied\" };\n }\n const documentId = extractSingleDocumentId(req);\n if (documentId === null) return { kind: \"denied\" };\n\n if (params.has(\"signature\") || params.has(\"expires\")) {\n const signature = singleQueryValue(params, \"signature\");\n const expires = singleQueryValue(params, \"expires\");\n if (!urlSigner || signature === null || expires === null) {\n return { kind: \"denied\" };\n }\n return urlSigner.verify(hash, documentId, expires, signature)\n ? { kind: \"granted\", documentId }\n : { kind: \"denied\" };\n }\n\n let decision;\n try {\n decision = await attachmentAccess.canReadAttachment({\n documentId,\n attachmentRef: createRef(hash),\n userAddress: actor?.user?.address,\n appKey: actor?.user?.appKey,\n });\n } catch (err) {\n logger.error(\"Attachment access decision failed: @error\", err);\n return { kind: \"error\" };\n }\n if (decision.kind === \"projection-unavailable\") {\n return { kind: \"unavailable\" };\n }\n if (decision.kind === \"denied\") return { kind: \"denied\" };\n return { kind: \"granted\", documentId: decision.documentId };\n}\n\n/** Answers a refused grant; true when the request may proceed. */\nfunction admitGrant(\n res: ServerResponse,\n grant: ByteGrant,\n): grant is { kind: \"granted\"; documentId: string } {\n switch (grant.kind) {\n case \"granted\":\n return true;\n case \"denied\":\n // 404, never 403: a refusal must not reveal that the hash exists.\n sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);\n return false;\n case \"unavailable\":\n sendError(res, 503, \"Attachment downloads are temporarily unavailable\");\n return false;\n case \"error\":\n sendError(res, 500, \"Internal error\");\n return false;\n }\n}\n\n/**\n * Base URL of this Switchboard as seen by the caller, used to build\n * filesystem `switchboard` download targets that point back at the signed\n * byte route.\n */\nfunction requestBaseUrl(req: IncomingMessage): string | null {\n const forwardedProto = req.headers[\"x-forwarded-proto\"];\n const proto =\n (Array.isArray(forwardedProto) ? forwardedProto[0] : forwardedProto)\n ?.split(\",\")[0]\n ?.trim() ||\n ((req.socket as { encrypted?: boolean }).encrypted ? \"https\" : \"http\");\n const forwardedHost = req.headers[\"x-forwarded-host\"];\n const host =\n (Array.isArray(forwardedHost) ? forwardedHost[0] : forwardedHost) ??\n req.headers.host;\n if (!host) return null;\n return `${proto}://${host}`;\n}\n\nexport function makeDownloadTargetHandler(\n attachments: AttachmentBuildResult,\n attachmentAccess: IAttachmentAccessService,\n urlSigner: AttachmentUrlSigner | null,\n) {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n _body?: unknown,\n actor?: AttachmentActorContext,\n ): Promise<void> => {\n // Target responses carry short-lived URLs and authorization decisions;\n // no intermediary may cache them.\n res.setHeader(\"Cache-Control\", \"no-store\");\n\n const hash = extractParam(req, \"hash\");\n if (!hash || !HASH_PATTERN.test(hash)) {\n sendError(res, 400, \"Invalid attachment hash\");\n return;\n }\n const documentId = extractSingleDocumentId(req);\n if (documentId === null) {\n sendError(\n res,\n 400,\n \"documentId is required exactly once as a non-empty query parameter\",\n );\n return;\n }\n const expiresIn = extractExpiresIn(req);\n if (expiresIn === \"invalid\") {\n sendError(\n res,\n 400,\n \"expiresIn must be a single positive integer number of seconds\",\n );\n return;\n }\n\n const canonicalHash = hash.toLowerCase() as AttachmentHash;\n let decision;\n try {\n decision = await attachmentAccess.canReadAttachment({\n documentId,\n attachmentRef: createRef(canonicalHash),\n userAddress: actor?.user?.address,\n appKey: actor?.user?.appKey,\n });\n } catch (err) {\n logger.error(\"Attachment access decision failed: @error\", err);\n sendError(res, 500, \"Internal error\");\n return;\n }\n\n if (decision.kind === \"projection-unavailable\") {\n sendError(res, 503, \"Attachment downloads are temporarily unavailable\");\n return;\n }\n if (decision.kind === \"denied\") {\n sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);\n return;\n }\n\n let header;\n try {\n header = await attachments.store.stat(canonicalHash);\n } catch (err) {\n if (err instanceof AttachmentNotFound) {\n sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);\n return;\n }\n logger.error(\"Attachment metadata lookup failed: @error\", err);\n sendError(res, 500, \"Internal error\");\n return;\n }\n if (header.status !== \"available\") {\n sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);\n return;\n }\n\n let target: AttachmentDownloadTarget;\n if (attachments.backend && attachments.backend.kind !== \"filesystem\") {\n try {\n target = await attachments.backend.prepareDownloadTarget(\n canonicalHash,\n expiresIn,\n );\n } catch {\n // Backend errors are sanitized at the backend boundary; no URLs or\n // signatures reach this scope, and none may be logged from here.\n sendError(res, 502, \"Attachment download target unavailable\");\n return;\n }\n } else {\n if (!urlSigner) {\n sendError(res, 503, \"Attachment download signing is not configured\");\n return;\n }\n const base = requestBaseUrl(req);\n if (!base) {\n sendError(res, 500, \"Internal error\");\n return;\n }\n const signed = urlSigner.sign(\n canonicalHash,\n decision.documentId,\n expiresIn,\n );\n try {\n target = parseAttachmentDownloadTarget({\n kind: \"switchboard\",\n method: \"GET\",\n url: `${base}/attachments/${canonicalHash}?${signed.query}`,\n headers: {},\n expiresAtUtc: signed.expiresAtUtc,\n });\n } catch {\n sendError(res, 500, \"Internal error\");\n return;\n }\n }\n\n sendJson(res, 200, target);\n };\n}\n","import type { AttachmentHash } from \"@powerhousedao/reactor\";\nimport { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\n\nexport const ATTACHMENT_URL_SIGNING_SECRET_ENV =\n \"PH_ATTACHMENT_URL_SIGNING_SECRET\";\n\nconst MIN_SECRET_LENGTH = 32;\nconst EXPIRES_PATTERN = /^[1-9]\\d{0,15}$/;\nconst SIGNATURE_PATTERN = /^[A-Za-z0-9_-]{43}$/;\n\nexport type SignedAttachmentUrl = {\n query: string;\n expiresAtUtc: string;\n};\n\n// The filesystem counterpart of an S3 presigned GET.\nexport class AttachmentUrlSigner {\n constructor(\n private readonly secret: string | Buffer,\n private readonly now: () => number = Date.now,\n ) {}\n\n sign(\n hash: AttachmentHash,\n documentId: string,\n ttlSeconds: number,\n ): SignedAttachmentUrl {\n const expires = Math.floor(this.now() / 1000) + ttlSeconds;\n const params = new URLSearchParams({\n documentId,\n expires: String(expires),\n signature: this.mac(hash, documentId, String(expires)),\n });\n return {\n query: params.toString(),\n expiresAtUtc: new Date(expires * 1000).toISOString(),\n };\n }\n\n verify(\n hash: AttachmentHash,\n documentId: string,\n expires: string,\n signature: string,\n ): boolean {\n if (!EXPIRES_PATTERN.test(expires) || !SIGNATURE_PATTERN.test(signature)) {\n return false;\n }\n if (Number(expires) * 1000 <= this.now()) {\n return false;\n }\n const expected = Buffer.from(this.mac(hash, documentId, expires));\n const presented = Buffer.from(signature);\n return (\n expected.length === presented.length &&\n timingSafeEqual(expected, presented)\n );\n }\n\n private mac(hash: string, documentId: string, expires: string): string {\n return createHmac(\"sha256\", this.secret)\n .update(\n JSON.stringify([\"attachment-download/v1\", hash, documentId, expires]),\n )\n .digest(\"base64url\");\n }\n}\n\nexport type AttachmentUrlSigning =\n | { status: \"configured\"; signer: AttachmentUrlSigner }\n | { status: \"ephemeral\"; signer: AttachmentUrlSigner }\n | { status: \"unconfigured\" };\n\n// Unset: production fails closed, anything else gets a per-process secret.\nexport function resolveAttachmentUrlSigning(\n env: Readonly<Record<string, string | undefined>> = process.env,\n): AttachmentUrlSigning {\n const secret = env[ATTACHMENT_URL_SIGNING_SECRET_ENV];\n if (secret !== undefined) {\n if (secret.trim() !== secret || secret.length < MIN_SECRET_LENGTH) {\n throw new Error(\n `${ATTACHMENT_URL_SIGNING_SECRET_ENV} must be at least ${MIN_SECRET_LENGTH} characters with no leading or trailing whitespace`,\n );\n }\n return { status: \"configured\", signer: new AttachmentUrlSigner(secret) };\n }\n if (env.NODE_ENV === \"production\") {\n return { status: \"unconfigured\" };\n }\n return {\n status: \"ephemeral\",\n signer: new AttachmentUrlSigner(randomBytes(32)),\n };\n}\n","import type { API } from \"@powerhousedao/reactor-api\";\nimport { childLogger } from \"document-model\";\nimport { mountAuthenticatedNodeRoute } from \"./mount-auth.js\";\nimport {\n makeDeleteReservationHandler,\n makeDownloadHandler,\n makeDownloadTargetHandler,\n makeGetReservationHandler,\n makeReserveHandler,\n makeStatHandler,\n makeUploadHandler,\n} from \"./routes.js\";\nimport {\n ATTACHMENT_URL_SIGNING_SECRET_ENV,\n resolveAttachmentUrlSigning,\n type AttachmentUrlSigner,\n} from \"./url-signer.js\";\n\nconst logger = childLogger([\"switchboard\", \"attachments\"]);\n\nexport type RegisterAttachmentRoutesOptions = {\n /** Overrides the signer resolved from the environment; null disables signing. */\n urlSigner?: AttachmentUrlSigner | null;\n};\n\nexport function registerAttachmentRoutes(\n api: API,\n options: RegisterAttachmentRoutesOptions = {},\n): void {\n const { attachments, attachmentAccess } = api;\n const urlSigner =\n options.urlSigner === undefined\n ? signerFromEnvironment(attachments.backend?.kind ?? \"filesystem\")\n : options.urlSigner;\n\n mountAuthenticatedNodeRoute(\n api,\n \"POST\",\n \"/attachments/reservations\",\n makeReserveHandler(attachments),\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"GET\",\n \"/attachments/reservations/:reservationId\",\n makeGetReservationHandler(attachments),\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"DELETE\",\n \"/attachments/reservations/:reservationId\",\n makeDeleteReservationHandler(attachments),\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"PUT\",\n \"/attachments/reservations/:reservationId\",\n makeUploadHandler(attachments),\n // Streams to storage; no parser may buffer or drain the body first.\n { rawBody: true },\n );\n\n // Anonymous-capable: authorization is purely the document's (or a signed\n // URL minted under it), exactly as it is for the document itself.\n mountAuthenticatedNodeRoute(\n api,\n \"HEAD\",\n \"/attachments/:hash\",\n makeStatHandler(attachments, attachmentAccess, urlSigner),\n { allowAnonymous: true },\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"GET\",\n \"/attachments/:hash/download-target\",\n makeDownloadTargetHandler(attachments, attachmentAccess, urlSigner),\n { allowAnonymous: true },\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"GET\",\n \"/attachments/:hash\",\n makeDownloadHandler(attachments, attachmentAccess, urlSigner),\n { allowAnonymous: true },\n );\n}\n\nfunction signerFromEnvironment(\n backend: \"filesystem\" | \"s3\",\n): AttachmentUrlSigner | null {\n const signing = resolveAttachmentUrlSigning();\n if (signing.status === \"unconfigured\") {\n if (backend === \"filesystem\") {\n logger.error(\n `${ATTACHMENT_URL_SIGNING_SECRET_ENV} is not set: filesystem attachment download targets are refused until it is`,\n );\n }\n return null;\n }\n if (signing.status === \"ephemeral\" && backend === \"filesystem\") {\n logger.warn(\n `${ATTACHMENT_URL_SIGNING_SECRET_ENV} is not set: signing attachment download URLs with a per-process secret`,\n );\n }\n return signing.signer;\n}\n","import {\n REACTOR_SCHEMA,\n supportsLiveReadModelRegistration,\n type DocumentViewDatabase,\n type InProcessReactorClientModule,\n type ReactorBuilder,\n} from \"@powerhousedao/reactor\";\nimport type { AttachmentReferenceProjectionCapability } from \"@powerhousedao/reactor-api\";\nimport {\n AttachmentReferenceReadModel,\n AttachmentSchemaCompiler,\n type IAttachmentReferenceWriter,\n} from \"@powerhousedao/reactor-attachments\";\nimport type { Kysely } from \"kysely\";\n\nexport type AttachmentReferenceReadModelRegistration = {\n attachmentReferenceWriter: IAttachmentReferenceWriter;\n baseKysely: Kysely<unknown>;\n};\n\nconst attachmentSchemaCompiler = new AttachmentSchemaCompiler();\n\nfunction createAttachmentReferenceReadModel(\n baseKysely: Kysely<unknown>,\n dependencies: {\n operationIndex: ConstructorParameters<\n typeof AttachmentReferenceReadModel\n >[1];\n writeCache: ConstructorParameters<typeof AttachmentReferenceReadModel>[2];\n processorManagerConsistencyTracker: ConstructorParameters<\n typeof AttachmentReferenceReadModel\n >[3];\n documentModelRegistry: ConstructorParameters<\n typeof AttachmentReferenceReadModel\n >[4];\n },\n attachmentReferenceWriter: IAttachmentReferenceWriter,\n): AttachmentReferenceReadModel {\n return new AttachmentReferenceReadModel(\n baseKysely.withSchema(\n REACTOR_SCHEMA,\n ) as unknown as Kysely<DocumentViewDatabase>,\n dependencies.operationIndex,\n dependencies.writeCache,\n dependencies.processorManagerConsistencyTracker,\n dependencies.documentModelRegistry,\n attachmentSchemaCompiler,\n attachmentReferenceWriter,\n );\n}\n\nexport function registerAttachmentReferenceReadModel(\n reactorBuilder: ReactorBuilder,\n registration: AttachmentReferenceReadModelRegistration,\n): void {\n reactorBuilder.withReadModelFactory(\n async ({\n documentModelRegistry,\n operationIndex,\n writeCache,\n processorManagerConsistencyTracker,\n }) => {\n const readModel = createAttachmentReferenceReadModel(\n registration.baseKysely,\n {\n operationIndex,\n writeCache,\n processorManagerConsistencyTracker,\n documentModelRegistry,\n },\n registration.attachmentReferenceWriter,\n );\n await readModel.init();\n return readModel;\n },\n );\n}\n\nexport async function registerAttachmentReferenceReadModelOnModule(\n clientModule: InProcessReactorClientModule,\n attachmentReferenceWriter: IAttachmentReferenceWriter,\n): Promise<AttachmentReferenceProjectionCapability> {\n const reactorModule = clientModule.reactorModule;\n if (!reactorModule) {\n return {\n status: \"unavailable\",\n reason: \"in-process-reactor-module-unavailable\",\n };\n }\n\n const coordinator = reactorModule.readModelCoordinator;\n if (!supportsLiveReadModelRegistration(coordinator)) {\n return {\n status: \"unavailable\",\n reason: \"live-read-model-registration-unsupported\",\n };\n }\n\n const readModel = createAttachmentReferenceReadModel(\n reactorModule.database as unknown as Kysely<unknown>,\n {\n operationIndex: reactorModule.operationIndex,\n writeCache: reactorModule.writeCache,\n processorManagerConsistencyTracker:\n reactorModule.processorManagerConsistencyTracker,\n documentModelRegistry: reactorModule.documentModelRegistry,\n },\n attachmentReferenceWriter,\n );\n\n await readModel.init();\n coordinator.addReadModel(readModel, \"pre_ready\");\n await readModel.init();\n\n return { status: \"available\" };\n}\n","import type {\n ReactorBuilder,\n ReactorFeatureFlags,\n} from \"@powerhousedao/reactor\";\nimport {\n ChannelScheme,\n type IDocumentModelLoader,\n type ReactorClientBuilder,\n type SignerConfig,\n} from \"@powerhousedao/reactor\";\nimport {\n baseDocumentModels,\n getUniqueDocumentModels,\n} from \"@powerhousedao/reactor-api\";\nimport type {\n DocumentModelModule,\n SignaturePolicy,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport type { ILogger } from \"document-model\";\n\nexport type SwitchboardReactorDefaultsOptions = {\n // Extra models registered alongside the baseline (document-model, drive,\n // reactor-drive, reactor-group). Pass vetra models here in studio/dev.\n // Deduped by id.\n documentModels?: DocumentModelModule[];\n /** Upgrade manifests for versioned models, one per document type. */\n upgradeManifests?: UpgradeManifest<readonly number[]>[];\n /** Default true. */\n includeBaseModels?: boolean;\n /**\n * Channel scheme. Defaults to `ChannelScheme.SWITCHBOARD`, which populates\n * `reactorModule.syncModule.syncManager` — required by reactor-api. Set\n * to `false` if the caller configures sync itself (`withChannelScheme` or\n * `withSync`); the builder refuses both together.\n */\n channelScheme?: ChannelScheme | false;\n /** Defaults to true. Set false when the caller owns SIGINT handling. */\n signalHandlers?: boolean;\n /** Executor tuning. Omit to use the reactor's own defaults. */\n executorConfig?: {\n maxSkipThreshold?: number;\n featureFlags?: Partial<ReactorFeatureFlags>;\n };\n /** Wire dynamic document-model loading via HTTP. */\n documentModelLoader?: IDocumentModelLoader;\n logger?: ILogger;\n /**\n * Identity signer (typically from `getRenownSignerConfig`). Signs client\n * writes and the operations the executor synthesizes, in pooled workers\n * through `workerSigner`; omit for unsigned operation.\n */\n signer?: SignerConfig;\n /**\n * Which keys may sign as which users (typically from\n * `getRenownTrustPolicyConfig`); wins over one carried by `signer`.\n */\n trustPolicy?: Pick<SignerConfig, \"trustPolicy\" | \"workerTrustPolicy\">;\n /** What the client creates new documents as; see `resolveCreateSignaturePolicy`. */\n createSignaturePolicy?: SignaturePolicy;\n};\n\n/**\n * Apply switchboard's standard configuration to a reactor + client builder\n * pair. Each piece is opt-out via the options object; defaults mirror what\n * `startSwitchboard` does when building a reactor itself. Mutates both\n * builders in place.\n *\n * Does NOT touch kysely or read models — callers wire those themselves\n * (see `withKysely` / `withReadModelFactory` on the reactor builder).\n */\n/** The models switchboard always registers alongside package models. */\nexport function switchboardBaseDocumentModels() {\n return baseDocumentModels.map(([, model]) => model);\n}\n\nexport function applySwitchboardReactorDefaults(\n reactorBuilder: ReactorBuilder,\n clientBuilder: ReactorClientBuilder,\n options: SwitchboardReactorDefaultsOptions = {},\n): void {\n const baseModels =\n options.includeBaseModels !== false ? switchboardBaseDocumentModels() : [];\n const extra = options.documentModels ?? [];\n if (baseModels.length || extra.length) {\n reactorBuilder.withDocumentModelSources(\n getUniqueDocumentModels(baseModels, extra),\n );\n }\n\n if (options.upgradeManifests?.length) {\n reactorBuilder.withUpgradeManifests(options.upgradeManifests);\n }\n\n const scheme =\n options.channelScheme === undefined\n ? ChannelScheme.SWITCHBOARD\n : options.channelScheme;\n if (scheme !== false) {\n reactorBuilder.withChannelScheme(scheme);\n }\n\n if (options.signalHandlers !== false) {\n reactorBuilder.withSignalHandlers();\n }\n\n if (\n options.executorConfig?.maxSkipThreshold !== undefined ||\n options.executorConfig?.featureFlags !== undefined\n ) {\n reactorBuilder.withExecutorConfig({\n ...(options.executorConfig.maxSkipThreshold !== undefined\n ? { maxSkipThreshold: options.executorConfig.maxSkipThreshold }\n : {}),\n ...(options.executorConfig.featureFlags !== undefined\n ? { featureFlags: options.executorConfig.featureFlags }\n : {}),\n });\n }\n\n if (options.documentModelLoader) {\n reactorBuilder.withDocumentModelLoader(options.documentModelLoader);\n }\n\n if (options.logger) {\n reactorBuilder.withLogger(options.logger);\n }\n\n if (options.signer) {\n clientBuilder.withSigner(options.signer);\n reactorBuilder.withSigner(\n options.signer.signer,\n options.signer.workerSigner,\n );\n }\n\n if (options.createSignaturePolicy) {\n clientBuilder.withCreateSignaturePolicy(options.createSignaturePolicy);\n }\n\n const trust = options.trustPolicy ?? options.signer;\n if (trust?.trustPolicy) {\n reactorBuilder.withTrustPolicy(trust.trustPolicy, trust.workerTrustPolicy);\n }\n}\n","import { createRemoteAttachmentService } from \"@powerhousedao/reactor-attachments\";\nimport type { IRenown } from \"@renown/sdk\";\nimport type { HostPlugin } from \"@powerhousedao/host-core\";\nimport { registerAttachmentRoutes } from \"../attachments/index.js\";\nimport { deriveAttachmentServiceConfig } from \"../server.mjs\";\nimport type { SwitchboardHostContext } from \"../plugin-host.mjs\";\nimport { z } from \"zod\";\n\n/** No entry config: presence is the whole activation. A typo'd config key\n * fails at resolution instead of being silently ignored. */\nexport const attachmentsPluginConfigSchema = z.strictObject({});\n\nexport type AttachmentsPluginConfig = z.input<\n typeof attachmentsPluginConfigSchema\n>;\n\ndeclare global {\n interface PHPluginConfigs {\n \"@powerhousedao/switchboard/plugins/attachments\": AttachmentsPluginConfig;\n }\n}\n\n/**\n * R2.3 — the attachments subsystem as a built-in plugin: the six /attachments\n * routes mount at onHttpMounting and the remote attachment service is created\n * for the returned handle. Presence is activation — removed from the\n * composition, the routes and service do not exist. NOT yet carved: the\n * attachment-reference read model registered inside reactor construction\n * (carve map: server.mts initializeClient) — it follows with the\n * onReadModelsRegistering step in R2 step 2; until then it registers on both\n * paths (a dormant read model when the plugin is absent, harmless).\n *\n * Inputs (carve map): api (routes), options.attachmentServiceUrl /\n * PH_SWITCHBOARD_PUBLIC_URL / https + serverPort + renown (service config).\n */\nexport const attachmentsPlugin: HostPlugin<{\n onHttpMounting: (ctx: SwitchboardHostContext) => void;\n}> = {\n name: \"switchboard-attachments\",\n appliesTo: \"switchboard\",\n configSchema: attachmentsPluginConfigSchema,\n hooks: {\n onHttpMounting: (ctx) => {\n registerAttachmentRoutes(\n ctx.api as Parameters<typeof registerAttachmentRoutes>[0],\n );\n ctx.attachmentService = createRemoteAttachmentService(\n deriveAttachmentServiceConfig(\n ctx.options as { attachmentServiceUrl?: string; https?: boolean },\n ctx.serverPort as number,\n ctx.renown as IRenown | null,\n ),\n );\n },\n },\n};\n\n// resolveHostPlugins consumes the DEFAULT export (plugin object or factory).\nexport default attachmentsPlugin;\n","import { attachmentsPlugin } from \"./plugins/attachments.mjs\";\nimport { privacyPlugin } from \"./plugins/privacy.mjs\";\nimport { workflowsPlugin } from \"./plugins/workflows.mjs\";\nimport { mcpPlugin } from \"./plugins/mcp.mjs\";\nimport {\n mergeContributions,\n resolveOrder,\n runObserveHook,\n runObserveHookSequential,\n runTransformHook,\n type HostPlugin,\n type MergedContribution,\n type ResolvedPlugin,\n} from \"@powerhousedao/host-core\";\n\n/**\n * R2 — SwitchboardCore's plugin pipeline (rewire plan, carve map:\n * uniform-runners-plan/rewire/r2-carve-map.md). Behind\n * FEATURE_PLUGIN_HOST_ENABLED: flag off, startSwitchboard runs the existing\n * inline path byte-identically; flag on, the five subsystems run as built-in\n * plugins through these hook moments. Subsystems carve one per commit; until\n * a subsystem is carved, its inline code runs on BOTH paths and its plugin\n * twin does not exist.\n *\n * Hook vocabulary (SwitchboardHooks), anchored to the boot spine:\n * - transformServerOptions — after option/flag resolution, before anything opens\n * - onReadModelsRegistering — inside reactor construction (build-time read models)\n * - onHttpMounting — api exists; routes mount here\n * - onSubgraphsRegistering — push into lateSubgraphs before the drain\n * - onReactorReady — client + graphqlManager destructured\n * - onDrivesReady — after core drive seeding / remote attachment\n * - onShutdown — first in the subsystem-ordered teardown\n */\n\nexport const PLUGIN_HOST_FLAG = \"FEATURE_PLUGIN_HOST_ENABLED\";\n\nexport function isPluginHostEnabled(\n env: Record<string, string | undefined> = process.env,\n): boolean {\n const value = env[PLUGIN_HOST_FLAG]?.trim().toLowerCase();\n return value === \"1\" || value === \"true\";\n}\n\n/**\n * The context plugins receive. Fields are populated as the boot spine reaches\n * them (api/client/graphqlManager are undefined before stage 17); concrete\n * types stay in server.mts — subsystem carves tighten their own slices.\n */\nexport interface SwitchboardHostContext {\n /** The switchboard's ILogger; typed loosely here to avoid pinning the\n * logger package in the scaffold — subsystem carves use it as-is. */\n logger: unknown;\n options: Record<string, unknown>;\n renown: unknown;\n serverPort?: number;\n /** Set by the attachments plugin at onHttpMounting; the boot reads it for\n * the returned handle. */\n attachmentService?: unknown;\n /** Privacy plugin state: config resolved at transformServerOptions\n * (fail-fast), the running subsystem set at onSubgraphsRegistering. */\n privacyConfig?: unknown;\n privacy?: unknown;\n /** Workflows plugin: wiring closures handed in by server.mts, runtime +\n * retry handles stored by the plugin. */\n workflowsOrchestration?: unknown;\n workflows?: unknown;\n workflowsRetry?: unknown;\n api?: unknown;\n client?: unknown;\n graphqlManager?: unknown;\n reactorClientModule?: unknown;\n /** Late subgraph registrations drain before the readiness router update. */\n lateSubgraphs?: Promise<unknown>[];\n contributions: Record<string, MergedContribution[]>;\n}\n\nexport interface SwitchboardPluginHost {\n readonly plugins: readonly HostPlugin[];\n readonly ctx: SwitchboardHostContext;\n transformOptions<T>(seed: T): Promise<T>;\n observe(\n hook:\n | \"onReadModelsRegistering\"\n | \"onHttpMounting\"\n | \"onSubgraphsRegistering\"\n | \"onReactorReady\"\n | \"onDrivesReady\"\n | \"onShutdown\",\n ): Promise<void>;\n}\n\n/** Built-in plugins, pre-listed (the default composition until host.js\n * entries map in R2 step 2). Subsystems join as R2 carves them. */\nexport function builtinSwitchboardPlugins(): ResolvedPlugin[] {\n const entry = { enabled: true, verbs: \"*\" as const, config: {} };\n return [\n {\n plugin: mcpPlugin as HostPlugin,\n provenance: \"built-in\",\n entry: { ...entry, module: \"@powerhousedao/switchboard/plugins/mcp\" },\n },\n {\n plugin: attachmentsPlugin as HostPlugin,\n provenance: \"built-in\",\n entry: {\n ...entry,\n module: \"@powerhousedao/switchboard/plugins/attachments\",\n },\n },\n {\n plugin: privacyPlugin as HostPlugin,\n provenance: \"built-in\",\n entry: {\n ...entry,\n module: \"@powerhousedao/switchboard/plugins/privacy\",\n },\n },\n // Registered after privacy ON PURPOSE: onShutdown runs sequentially in\n // registration order, preserving the inline teardown (privacy stops\n // before workflows, both before api.dispose — carve map).\n {\n plugin: workflowsPlugin as HostPlugin,\n provenance: \"built-in\",\n entry: {\n ...entry,\n module: \"@powerhousedao/switchboard/plugins/workflows\",\n },\n },\n ];\n}\n\nexport function createSwitchboardPluginHost(\n ctx: Omit<SwitchboardHostContext, \"contributions\">,\n resolved?: readonly ResolvedPlugin[],\n): SwitchboardPluginHost {\n resolved ??= builtinSwitchboardPlugins();\n const ordered = resolveOrder(resolved.map((r) => r.plugin));\n const contributions = mergeContributions(\n resolved.map((r) => ({ plugin: r.plugin, provenance: r.provenance })),\n );\n const fullCtx: SwitchboardHostContext = { ...ctx, contributions };\n\n // Change 2: the composition is observable on the `ph run` terminal. Report\n // the activated plugins once at construction, then which plugins run each\n // lifecycle hook as it fires.\n const LOG = \"[switchboard:plugins]\";\n console.log(\n `${LOG} composition: ${ordered.length} plugin(s) in order — ${ordered.map((p) => p.name).join(\", \") || \"(none)\"}`,\n );\n for (const r of resolved) {\n const cfg = Object.keys(r.entry.config ?? {});\n console.log(\n `${LOG} • ${r.plugin.name} [${r.provenance}] (${r.entry.module})` +\n (cfg.length ? ` config: {${cfg.join(\", \")}}` : \"\"),\n );\n }\n const ranBy = (hook: string) =>\n ordered.filter((p) => (p.hooks as Record<string, unknown>)?.[hook]);\n const logHook = (hook: string) => {\n const names = ranBy(hook).map((p) => p.name);\n console.log(\n `${LOG} hook ${hook} → ${names.length ? names.join(\", \") : \"(no implementers)\"}`,\n );\n };\n\n return {\n plugins: ordered,\n ctx: fullCtx,\n transformOptions: (seed) => {\n logHook(\"transformServerOptions\");\n return runTransformHook(\"transformServerOptions\", ordered, fullCtx, seed);\n },\n observe: (hook) => {\n logHook(hook);\n return hook === \"onShutdown\"\n ? runObserveHookSequential(hook, ordered, fullCtx)\n : runObserveHook(hook, ordered, fullCtx);\n },\n };\n}\n","import type { InspectionThrottleConfig } from \"@powerhousedao/reactor-api\";\nimport { parseNonNegativeInt } from \"./env.mjs\";\n\nconst NAME = \"PH_INSPECTION_CALLS_PER_MINUTE\";\n\n/** Unset keeps reactor-api's default; an invalid value fails boot. */\nexport function inspectionThrottleFromEnv(\n env: NodeJS.ProcessEnv,\n): Partial<InspectionThrottleConfig> {\n const callsPerMinute = parseNonNegativeInt(env[NAME], NAME);\n if (callsPerMinute === undefined) {\n return {};\n }\n if (callsPerMinute < 1) {\n throw new Error(`${NAME} must be at least 1, got \"${env[NAME]}\"`);\n }\n return { callsPerMinute };\n}\n","import { EnvVarProvider } from \"@openfeature/env-var-provider\";\nimport { OpenFeature } from \"@openfeature/server-sdk\";\n\nexport async function initFeatureFlags() {\n // for now, we're only using env vars for feature flags\n const provider = new EnvVarProvider();\n\n await OpenFeature.setProviderAndWait(provider);\n\n return OpenFeature.getClient();\n}\n","import type { BooleanFlagSource } from \"./workflow-runtime.mjs\";\n\n/** The env var and OpenFeature flag key that can keep the inspection subgraph unmounted. */\nexport const INSPECTION_ENABLED = \"INSPECTION_ENABLED\";\n\n/** Whether `/graphql/inspection` is mounted when neither the host nor INSPECTION_ENABLED says. */\nexport const INSPECTION_ENABLED_DEFAULT = true;\n\nexport interface InspectionFlagInput {\n featureFlags: BooleanFlagSource;\n /** The host's `inspection` option. */\n option?: boolean;\n}\n\n/** Whether to mount `/graphql/inspection`. A host's `inspection: false` wins;\n * otherwise INSPECTION_ENABLED decides, falling back to the host's option and\n * then INSPECTION_ENABLED_DEFAULT. */\nexport async function resolveInspectionEnabled({\n featureFlags,\n option,\n}: InspectionFlagInput): Promise<boolean> {\n if (option === false) return false;\n return featureFlags.getBooleanValue(\n INSPECTION_ENABLED,\n option ?? INSPECTION_ENABLED_DEFAULT,\n );\n}\n","import type { BooleanFlagSource } from \"./workflow-runtime.mjs\";\n\n/** The env var and OpenFeature flag key that can keep the MCP server unmounted. */\nexport const MCP_ENABLED = \"MCP_ENABLED\";\n\nexport interface McpFlagInput {\n featureFlags: BooleanFlagSource;\n /** The host's `mcp` option. */\n option?: boolean;\n}\n\n/** Whether to mount the MCP server at `/mcp`. On unless the host passes\n * `mcp: false` or MCP_ENABLED is \"false\": the env var can turn a host's MCP\n * off, never on, so a deployment that serves no MCP client can close the\n * endpoint without the bin growing a flag of its own. */\nexport async function resolveMcpEnabled({\n featureFlags,\n option,\n}: McpFlagInput): Promise<boolean> {\n if (option === false) return false;\n return featureFlags.getBooleanValue(MCP_ENABLED, true);\n}\n","import {\n HardenedPGliteDialect,\n type HardenedPGliteDialectOptions,\n} from \"@powerhousedao/reactor\";\nimport type {\n DatabaseIntrospector,\n Dialect,\n DialectAdapter,\n Driver,\n QueryCompiler,\n} from \"kysely\";\nimport type { ILogger } from \"document-model\";\nimport type { PGliteLike } from \"@powerhousedao/reactor-api/pglite-node\";\nimport { triggerFatalShutdown } from \"./fatal-shutdown.mjs\";\n\ntype FatalProcess = Parameters<typeof triggerFatalShutdown>[2];\n\n/** A poisoned store cannot recover in process, so it takes the fatal shutdown and a supervisor restart. */\nexport function reactorPgliteDialectOptions(\n logger: ILogger,\n proc?: FatalProcess,\n): Partial<HardenedPGliteDialectOptions> {\n return {\n onDiagnostic: (message, error) =>\n logger.error(`[pglite-dialect] ${message}: @error`, error),\n onPoisoned: (cause) => {\n if (!triggerFatalShutdown(\"PGlite session poisoned\", cause, proc)) {\n logger.error(\"PGlite session poisoned: @error\", cause);\n }\n },\n };\n}\n\ntype IntrospectedDatabase = Parameters<Dialect[\"createIntrospector\"]>[0];\n\n// kysely-pglite-dialect's driver.destroy() only nulls its reference to the\n// PGlite client — it never calls pglite.close(). Without close(), the store\n// misses its shutdown checkpoint and the next open runs WAL recovery. This\n// wrapper closes the dialect's PGlite as part of the reactor's\n// database.destroy() chain.\nexport class ClosablePGliteDialect implements Dialect {\n readonly #inner: HardenedPGliteDialect;\n readonly #pglite: PGliteLike;\n\n constructor(\n pglite: PGliteLike,\n options: Partial<HardenedPGliteDialectOptions> = {},\n ) {\n this.#pglite = pglite;\n this.#inner = new HardenedPGliteDialect(pglite, options);\n }\n\n createAdapter(): DialectAdapter {\n return this.#inner.createAdapter();\n }\n\n createDriver(): Driver {\n const driver = this.#inner.createDriver();\n const pglite = this.#pglite;\n const innerDestroy = driver.destroy.bind(driver);\n driver.destroy = async () => {\n await innerDestroy();\n if (pglite.closed) return;\n try {\n await pglite.close();\n } catch (err) {\n // An aborted runtime (Postgres PANIC) has nothing left to flush.\n if (!/PGlite aborted/.test(String(err))) throw err;\n }\n };\n return driver;\n }\n\n createQueryCompiler(): QueryCompiler {\n return this.#inner.createQueryCompiler();\n }\n\n createIntrospector(db: IntrospectedDatabase): DatabaseIntrospector {\n return this.#inner.createIntrospector(db);\n }\n}\n","import { syncTree } from \"@powerhousedao/reactor-api/pglite-node\";\nimport type { ILogger } from \"document-model\";\nimport { promises as fs } from \"node:fs\";\nimport {\n CURRENT_PG_MAJOR,\n isSupportedMajor,\n loadPGliteModule,\n loadPgDump,\n readPgVersionFile,\n type SupportedPgMajor,\n} from \"./pglite-version.js\";\n\ntype PGliteLike = {\n waitReady: Promise<void>;\n exec: (sql: string) => Promise<unknown>;\n close: () => Promise<void>;\n dumpDataDir: (compression: \"none\") => Promise<Blob>;\n};\n\ntype PGliteCtor = {\n new (dataDir: string, options?: Record<string, unknown>): PGliteLike;\n new (options: Record<string, unknown>): PGliteLike;\n};\n\nfunction backupPath(dataDir: string, major: number): string {\n const stamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n return `${dataDir}.backup-pg${major}-${stamp}`;\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await fs.stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction logRestoreFailure(\n dataDir: string,\n sql: string,\n err: unknown,\n logger: ILogger,\n): void {\n const errObj = err as {\n message?: string;\n position?: string | number;\n severity?: string;\n code?: string;\n detail?: string;\n where?: string;\n };\n const position =\n typeof errObj.position === \"string\"\n ? parseInt(errObj.position, 10)\n : typeof errObj.position === \"number\"\n ? errObj.position\n : NaN;\n\n logger.error(\n `[pglite-migration] Restore failed for ${dataDir}: code=${errObj.code ?? \"\"} severity=${errObj.severity ?? \"\"} message=${errObj.message ?? \"\"} sqlLength=${sql.length}`,\n );\n\n if (Number.isFinite(position) && position > 0) {\n const zeroBased = position - 1;\n const start = Math.max(0, zeroBased - 200);\n const end = Math.min(sql.length, zeroBased + 200);\n const before = sql.slice(start, zeroBased);\n const at = sql.slice(zeroBased, zeroBased + 1);\n const after = sql.slice(zeroBased + 1, end);\n logger.error(\n `[pglite-migration] SQL context around position ${position}:\\n${before}»${at}«${after}`,\n );\n } else {\n logger.error(\n `[pglite-migration] No position info. First 2000 chars of dump:\\n${sql.slice(0, 2000)}`,\n );\n }\n}\n\n/**\n * Migrate a filesystem PGLite data directory from a legacy PG major to the\n * current one. Renames the existing dir to a timestamped backup, dumps via the\n * matching legacy `pg_dump`, restores into a fresh current-version PGLite at\n * the original path. On failure, the original dir is restored from the backup.\n *\n * No-op when the dir is missing or already at the current major.\n */\nexport async function migratePgliteDir(\n dataDir: string,\n logger: ILogger,\n): Promise<void> {\n const major = await readPgVersionFile(dataDir);\n if (major === null) {\n logger.info(\n `[pglite-migration] No PG_VERSION at ${dataDir}; skipping migration`,\n );\n return;\n }\n if (major === CURRENT_PG_MAJOR) return;\n\n if (!isSupportedMajor(major)) {\n throw new Error(\n `Unsupported legacy PGlite data dir: PG_VERSION=${major} for ${dataDir}`,\n );\n }\n\n const backupDir = backupPath(dataDir, major);\n logger.info(\n `[pglite-migration] Migrating ${dataDir} from PG${major} to PG${CURRENT_PG_MAJOR}; backup: ${backupDir}`,\n );\n\n await fs.rename(dataDir, backupDir);\n\n let sql: string;\n try {\n const [legacyMod, pgDump] = await Promise.all([\n loadPGliteModule(major as SupportedPgMajor),\n loadPgDump(major as SupportedPgMajor),\n ]);\n const LegacyPGlite = (legacyMod as unknown as { PGlite: PGliteCtor })\n .PGlite;\n // pglite-tools 0.2.x talks to the server through files in the PGlite\n // FS, and 0.2.17's NODEFS write drops the view's byteOffset, so every\n // query arrives as zeros. Dump from an in-memory copy instead.\n const onDisk = new LegacyPGlite(backupDir);\n let tar: Blob;\n try {\n await onDisk.waitReady;\n tar = await onDisk.dumpDataDir(\"none\");\n } finally {\n await onDisk.close();\n }\n const pg = new LegacyPGlite({ loadDataDir: tar });\n try {\n await pg.waitReady;\n const file = await pgDump({ pg });\n sql = await file.text();\n } finally {\n await pg.close();\n }\n } catch (err) {\n await rollback(dataDir, backupDir, err, logger);\n throw err;\n }\n\n try {\n const currentMod = await loadPGliteModule(CURRENT_PG_MAJOR);\n const CurrentPGlite = (currentMod as unknown as { PGlite: PGliteCtor })\n .PGlite;\n // Stock NodeFS never syncs to the host; one pass after close does.\n const pg = new CurrentPGlite(dataDir, { relaxedDurability: false });\n try {\n await pg.waitReady;\n try {\n await pg.exec(\"SET standard_conforming_strings = off;\");\n } catch (gucErr) {\n logger.warn(\n `[pglite-migration] Could not force standard_conforming_strings=off: ${String(gucErr)}`,\n );\n }\n try {\n await pg.exec(sql);\n } catch (execErr) {\n logRestoreFailure(dataDir, sql, execErr, logger);\n throw execErr;\n }\n } finally {\n await pg.close();\n }\n syncTree(dataDir);\n } catch (err) {\n await rollback(dataDir, backupDir, err, logger);\n throw err;\n }\n\n logger.info(\n `[pglite-migration] Migration of ${dataDir} complete. Backup retained at ${backupDir}; remove it manually once you have verified the upgrade.`,\n );\n}\n\nasync function rollback(\n dataDir: string,\n backupDir: string,\n originalError: unknown,\n logger: ILogger,\n): Promise<void> {\n try {\n if (await pathExists(dataDir)) {\n await fs.rm(dataDir, { recursive: true, force: true });\n }\n if (await pathExists(backupDir)) {\n await fs.rename(backupDir, dataDir);\n }\n } catch (rollbackErr) {\n logger.error(\n `[pglite-migration] Migration AND rollback failed for ${dataDir}. Original error: ${String(originalError)}; rollback error: ${String(rollbackErr)}; backup may still exist at ${backupDir}.`,\n );\n return;\n }\n logger.error(\n `[pglite-migration] Migration failed for ${dataDir}; rolled back from ${backupDir}. Original error: ${String(originalError)}`,\n );\n}\n","import {\n preparePgliteDataDir,\n removeStalePgliteFiles,\n type ConversionDeps,\n} from \"@powerhousedao/reactor-api/pglite-node\";\nimport type { ILogger } from \"document-model\";\nimport { promises as fs } from \"node:fs\";\nimport { migratePgliteDir } from \"./pglite-migration.js\";\nimport {\n CURRENT_PG_MAJOR,\n openForVerify,\n readPgVersionFile,\n type SupportedPgMajor,\n} from \"./pglite-version.js\";\n\nexport interface PglitePreflightOptions {\n /** Local PGlite data dirs; Postgres URLs are already filtered out. */\n dirs: string[];\n forcePgVersion?: SupportedPgMajor;\n migratePglite?: boolean;\n /** PH_PGLITE_IN_MEMORY: the dirs are never opened, so nothing is touched. */\n inMemory: boolean;\n logger: ILogger;\n /** Test hook; defaults to the module-matched stock NodeFS. */\n openForVerify?: ConversionDeps[\"openForVerify\"];\n}\n\nconst RM_OPTIONS = {\n recursive: true,\n force: true,\n maxRetries: 10,\n retryDelay: 100,\n} as const;\n\n/**\n * Prepares every local PGlite dir before the first open and returns the\n * PG major detected on disk per dir. Conversion of an AtomicNodeFs snapshot\n * runs for every dir, before the major is read, so a pure-snapshot PG16 dir\n * is converted and then migrated.\n */\nexport async function runPglitePreflight(\n options: PglitePreflightOptions,\n): Promise<Map<string, number>> {\n const { dirs, logger } = options;\n const detectedMajors = new Map<string, number>();\n if (options.inMemory || dirs.length === 0) return detectedMajors;\n\n if (options.forcePgVersion !== undefined) {\n if (options.migratePglite) {\n logger.warn(\n \"PH_FORCE_PG_VERSION is set; ignoring --migrate-pglite/PH_MIGRATE_PGLITE because the data dirs will be wiped.\",\n );\n }\n logger.warn(\n `PH_FORCE_PG_VERSION=${options.forcePgVersion} set; wiping PGLite data dirs and re-initializing at PG${options.forcePgVersion}.`,\n );\n for (const dir of dirs) {\n // Conversion siblings go too, or the next boot refuses to initdb beside them.\n for (const p of [dir, `${dir}.converting`, `${dir}.old`]) {\n await fs.rm(p, RM_OPTIONS);\n }\n logger.info(`Wiped PGLite data dir ${dir}`);\n }\n return detectedMajors;\n }\n\n const deps: ConversionDeps = {\n openForVerify: options.openForVerify ?? openForVerify,\n logger,\n };\n for (const dir of dirs) {\n await preparePgliteDataDir(dir, deps);\n const major = await readPgVersionFile(dir);\n if (major !== null) detectedMajors.set(dir, major);\n }\n\n if (options.migratePglite) {\n for (const [dir, major] of detectedMajors) {\n if (major === CURRENT_PG_MAJOR) continue;\n await migratePgliteDir(dir, logger);\n // The migration's own close leaves a lockfile in the new dir.\n await removeStalePgliteFiles(dir, logger);\n const after = await readPgVersionFile(dir);\n if (after !== null) detectedMajors.set(dir, after);\n }\n } else {\n for (const [dir, major] of detectedMajors) {\n if (major === CURRENT_PG_MAJOR) continue;\n logger.warn(\n `PGLite data dir at ${dir} was created with PG${major} but Switchboard ships PG${CURRENT_PG_MAJOR}. Running on legacy PGLite. Re-start with --migrate-pglite (or PH_MIGRATE_PGLITE=true) to upgrade.`,\n );\n }\n }\n return detectedMajors;\n}\n","import type { PGliteOptions } from \"@electric-sql/pglite\";\nimport {\n createDurableNodeFs,\n PGLITE_UTC_PARSERS,\n pgliteWorkerEntryPath,\n resolvePgliteFsync,\n resolvePgliteWorkerMemoryMb,\n ThreadedPGlite,\n type DurableNodeFs,\n type PGliteAbortListener,\n type PGliteExitListener,\n type PGliteLike,\n type PGliteParserPreset,\n} from \"@powerhousedao/reactor-api/pglite-node\";\nimport type { HardenedPGliteDialectOptions } from \"@powerhousedao/reactor\";\nimport type { ILogger } from \"document-model\";\nimport { triggerFatalShutdown } from \"./fatal-shutdown.mjs\";\nimport {\n loadNodeFsClass,\n loadPGliteModule,\n pgliteModuleSpec,\n type SupportedPgMajor,\n} from \"./pglite-version.js\";\nimport type { BooleanFlagSource } from \"./workflow-runtime.mjs\";\n\ntype FatalProcess = Parameters<typeof triggerFatalShutdown>[2];\n\n/** The env var and OpenFeature flag key that moves each PGlite store into its own worker thread. */\nexport const PH_PGLITE_WORKERS = \"PH_PGLITE_WORKERS\";\n\n/** Whether PGlite stores run in worker threads when neither the host nor PH_PGLITE_WORKERS says. */\nexport const PGLITE_WORKERS_DEFAULT = true;\n\nexport interface PgliteWorkersFlagInput {\n featureFlags: BooleanFlagSource;\n /** The host's `pgliteWorkers` option; wins either way. */\n option?: boolean;\n}\n\n/** Whether each PGlite store opens in its own worker thread: the host's\n * option, else PH_PGLITE_WORKERS (\"true\"/\"false\"), else PGLITE_WORKERS_DEFAULT. */\nexport async function resolvePgliteWorkersEnabled({\n featureFlags,\n option,\n}: PgliteWorkersFlagInput): Promise<boolean> {\n if (option !== undefined) return option;\n return featureFlags.getBooleanValue(\n PH_PGLITE_WORKERS,\n PGLITE_WORKERS_DEFAULT,\n );\n}\n\n// A Postgres PANIC (ENOSPC on WAL, a failed fdatasync) aborts the wasm\n// runtime; the store is dead and the process must not keep accepting writes.\nexport function onPgliteAbort(\n logger: ILogger,\n what: unknown,\n proc?: FatalProcess,\n): void {\n if (!triggerFatalShutdown(\"PGlite aborted\", what, proc)) {\n logger.error(\"PGlite aborted: @error\", what);\n }\n}\n\n/** A store's worker thread died: every later query would fail, so the process shuts down. */\nexport function onPgliteWorkerExit(\n logger: ILogger,\n error: Error,\n proc?: FatalProcess,\n): void {\n if (!triggerFatalShutdown(\"PGlite worker exited\", error, proc)) {\n logger.error(\"PGlite worker exited: @error\", error);\n }\n}\n\n/** The events a worker-backed store raises; {@link ThreadedPGlite} has them. */\nexport interface PgliteWorkerEvents {\n onAbort(listener: PGliteAbortListener): () => void;\n onExit(listener: PGliteExitListener): () => void;\n}\n\n/** Sends a worker's abort and its unexpected exit to the fatal shutdown. */\nexport function routePgliteWorkerFailures(\n store: PgliteWorkerEvents,\n logger: ILogger,\n proc?: FatalProcess,\n): void {\n store.onAbort((reason) => onPgliteAbort(logger, reason, proc));\n store.onExit((error) => {\n if (error !== null) onPgliteWorkerExit(logger, error, proc);\n });\n}\n\n/** A store whose thread can be stopped at once. */\nexport interface TerminableStore {\n terminate(): Promise<void>;\n}\n\n/**\n * Adds a terminate of the store's worker to the dialect's `onPoisoned`: a\n * statement that never settled holds the worker's only connection, and the\n * fatal shutdown's close would otherwise queue behind it until its grace ran\n * out.\n */\nexport function terminateOnPoisoned(\n options: Partial<HardenedPGliteDialectOptions>,\n store: TerminableStore,\n): Partial<HardenedPGliteDialectOptions> {\n const reportPoisoned = options.onPoisoned;\n return {\n ...options,\n onPoisoned: (cause) => {\n reportPoisoned?.(cause);\n void store.terminate();\n },\n };\n}\n\n// 0.2.17 syncs WAL through open_datasync, which NODEFS cannot honour, so on\n// PG16 only checkpoints reach the host disk; commits are durable against an\n// app crash, not a power loss, until --migrate-pglite upgrades the dir.\nfunction pgliteFsyncFor(\n major: SupportedPgMajor,\n dir: string,\n logger: ILogger,\n): boolean {\n const wanted = resolvePgliteFsync(process.env);\n if (wanted && major === 16) {\n logger.warn(\n `PGlite data dir ${dir} is PG16 on pglite-legacy-02, which does not sync commits to disk; only checkpoints are synced until --migrate-pglite upgrades it.`,\n );\n }\n return wanted;\n}\n\n/** VACUUM FULL timing from the environment; unset or invalid keeps the defaults. */\nexport function vacuumFullTimingFromEnv(env: NodeJS.ProcessEnv): {\n vacuumFullQuietMs?: number;\n vacuumFullMaxDeferMs?: number;\n} {\n const ms = (value: string | undefined) => {\n if (value === undefined || value.trim() === \"\") return undefined;\n const parsed = Number(value);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;\n };\n const quiet = ms(env.PH_PGLITE_VACUUM_FULL_QUIET_MS);\n const maxDefer = ms(env.PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS);\n return {\n ...(quiet === undefined ? {} : { vacuumFullQuietMs: quiet }),\n ...(maxDefer === undefined ? {} : { vacuumFullMaxDeferMs: maxDefer }),\n };\n}\n\n/** Preloads the module's NodeFS so the returned factory can be synchronous. */\nexport async function loadDurableFsFactory(\n major: SupportedPgMajor,\n logger: ILogger,\n proc?: FatalProcess,\n): Promise<(dir: string) => DurableNodeFs> {\n const NodeFS = await loadNodeFsClass(major);\n const timing = vacuumFullTimingFromEnv(process.env);\n return (dir) =>\n createDurableNodeFs(NodeFS, dir, {\n fsync: pgliteFsyncFor(major, dir, logger),\n ...timing,\n logger,\n onAbort: (what) => onPgliteAbort(logger, what, proc),\n });\n}\n\nexport type PgliteStoreLabel = \"reactor-storage\" | \"read-storage\";\n\nexport interface PgliteStoreOptions {\n label: PgliteStoreLabel;\n major: SupportedPgMajor;\n parsers: PGliteParserPreset;\n /** PH_PGLITE_IN_MEMORY: the store ignores its dir. */\n inMemory: boolean;\n /** Open the store in its own worker thread (PH_PGLITE_WORKERS / `pgliteWorkers`). */\n threaded: boolean;\n logger: ILogger;\n /** Where fatal conditions go; the process by default. */\n proc?: FatalProcess;\n}\n\n/** Opens a store on a data dir; synchronous because reactor-api's read store opens synchronously. */\nexport type PgliteStoreFactory = (dataDir: string) => PGliteLike;\n\n/**\n * The factory for one PGlite store: in a worker thread when `threaded` (and a\n * worker script exists here), else in the main thread as before. Either way\n * the store runs DurableNodeFs over its dir with the same fsync choice, and a\n * wasm abort takes the fatal shutdown.\n */\nexport async function createPgliteStoreFactory(\n options: PgliteStoreOptions,\n): Promise<PgliteStoreFactory> {\n if (options.threaded) {\n if (pgliteWorkerEntryPath !== null) return threadedStoreFactory(options);\n options.logger.warn(\n `${options.label}: no PGlite worker script is available (unbuilt @powerhousedao/reactor-api); PGlite runs in the main thread`,\n );\n }\n return mainThreadStoreFactory(options);\n}\n\nfunction threadedStoreFactory(options: PgliteStoreOptions): PgliteStoreFactory {\n const { label, major, parsers, inMemory, logger, proc } = options;\n const memoryLimitMb = resolvePgliteWorkerMemoryMb(process.env);\n const module = pgliteModuleSpec(major);\n return (dir) => {\n const store = new ThreadedPGlite({\n store: {\n label,\n dataDir: inMemory ? null : dir,\n module,\n durableFs: inMemory\n ? null\n : {\n fsync: pgliteFsyncFor(major, dir, logger),\n ...vacuumFullTimingFromEnv(process.env),\n },\n parsers,\n },\n memoryLimitMb,\n logger,\n });\n routePgliteWorkerFailures(store, logger, proc);\n logger.info(\n `${label}: PGlite (PG${major}) in a worker thread (memory limit ${memoryLimitMb} MB)${where(inMemory, dir)}`,\n );\n return store;\n };\n}\n\nasync function mainThreadStoreFactory(\n options: PgliteStoreOptions,\n): Promise<PgliteStoreFactory> {\n const { label, major, inMemory, logger, proc } = options;\n const { PGlite } = await loadPGliteModule(major);\n const durableFs = inMemory\n ? null\n : await loadDurableFsFactory(major, logger, proc);\n const base: PGliteOptions =\n options.parsers === \"utc-timestamps\" ? { parsers: PGLITE_UTC_PARSERS } : {};\n return (dir) => {\n logger.info(\n `${label}: PGlite (PG${major}) in the main thread${where(inMemory, dir)}`,\n );\n return durableFs === null\n ? new PGlite(base)\n : new PGlite({ ...base, fs: durableFs(dir) });\n };\n}\n\nfunction where(inMemory: boolean, dir: string): string {\n return inMemory ? \", in memory [PH_PGLITE_IN_MEMORY=1]\" : ` at ${dir}`;\n}\n","import {\n DEFAULT_SIGNATURE_POLICY,\n isSignaturePolicy,\n type SignaturePolicy,\n} from \"@powerhousedao/shared/document-model\";\nimport type { ILogger } from \"document-model\";\n\n/**\n * What new documents are created as, from CREATE_SIGNATURE_POLICY. Without a\n * signer this switchboard cannot write to a v2-required document, so it falls\n * back to legacy and says so.\n */\nexport function resolveCreateSignaturePolicy(\n env: NodeJS.ProcessEnv,\n options: { hasSigner: boolean; logger?: Pick<ILogger, \"warn\"> },\n): SignaturePolicy {\n const raw = env.CREATE_SIGNATURE_POLICY?.trim();\n let policy: SignaturePolicy = DEFAULT_SIGNATURE_POLICY;\n if (raw) {\n if (!isSignaturePolicy(raw)) {\n throw new Error(\n `CREATE_SIGNATURE_POLICY must be \"legacy\" or \"v2-required\", got \"${raw}\"`,\n );\n }\n policy = raw;\n }\n\n if (policy === \"v2-required\" && !options.hasSigner) {\n options.logger?.warn(\n \"No signer is configured, so new documents are created legacy: a v2-required document refuses the unsigned operations this switchboard would write. Set up an identity (ph login) to create v2-required documents.\",\n );\n return \"legacy\";\n }\n return policy;\n}\n","import type { FactorySpec, SignerConfig } from \"@powerhousedao/reactor\";\nimport {\n createRenownTrustPolicy,\n DEFAULT_KEYPAIR_PATH,\n DEFAULT_RENOWN_URL,\n NodeKeyStorage,\n RenownBuilder,\n RenownCryptoBuilder,\n resolveSwitchboardEndpoint,\n type IRenown,\n type RenownTrustPolicyOptions,\n type SwitchboardRequestFn,\n} from \"@renown/sdk/node\";\nimport { resolvePhDir } from \"@powerhousedao/shared/clis/ph-dir\";\nimport { childLogger } from \"document-model\";\nimport { createRequire } from \"node:module\";\nimport { join, resolve } from \"node:path\";\n\nconst logger = childLogger([\"switchboard\", \"renown\"]);\n\nexport interface RenownOptions {\n /** Path to the keypair file. Defaults to .ph/.keypair.json in cwd */\n keypairPath?: string;\n /** If true, won't generate a new keypair if none exists */\n requireExisting?: boolean;\n /** Base url of the Renown instance to use */\n baseUrl?: string;\n /** Renown user storage. Defaults to .ph/.renown.json under PH_USER_DATA_DIR, else cwd */\n storagePath?: string;\n}\n\n/**\n * Initialize Renown for the Switchboard instance.\n * This allows Switchboard to authenticate with remote services\n * using the same identity established during `ph login`.\n */\nexport async function initRenown(\n options: RenownOptions = {},\n): Promise<IRenown | null> {\n const {\n keypairPath,\n requireExisting = false,\n baseUrl = DEFAULT_RENOWN_URL,\n storagePath = process.env.PH_USER_DATA_DIR\n ? join(resolvePhDir(), \".renown.json\")\n : undefined,\n } = options;\n\n const keyStorage = new NodeKeyStorage(keypairPath, {\n logger,\n });\n\n // Check if we have an existing keypair\n const existingKeyPair = await keyStorage.loadKeyPair();\n\n if (!existingKeyPair && requireExisting) {\n throw new Error(\n \"No existing keypair found and requireExisting is true. \" +\n 'Run \"ph login\" to create one.',\n );\n }\n\n if (!existingKeyPair) {\n logger.info(\"No existing keypair found. A new one will be generated.\");\n }\n\n const renownCrypto = await new RenownCryptoBuilder()\n .withKeyPairStorage(keyStorage)\n .build();\n\n // keyPath too: the builder's default key storage mkdirs <cwd>/.ph.\n const renown = await new RenownBuilder(\"switchboard\", {\n ...(storagePath ? { storagePath } : {}),\n ...(keypairPath ? { keyPath: keypairPath } : {}),\n })\n .withCrypto(renownCrypto)\n .withBaseUrl(baseUrl)\n .build();\n\n logger.info(\"Switchboard identity initialized: @did\", renownCrypto.did);\n\n return renown;\n}\n\n/**\n * Get the signer config for the given renown instance.\n *\n * @param renown - The renown instance\n * @param keypairPath - Where `initRenown` loaded the key from\n */\nexport function getRenownSignerConfig(\n renown: IRenown,\n keypairPath?: string,\n): SignerConfig {\n return {\n signer: renown.signer,\n workerSigner: getRenownWorkerSignerSpec(renown, keypairPath),\n };\n}\n\n/**\n * What a pooled executor worker imports to sign as this switchboard: it\n * reloads the key `initRenown` stored, and takes the user known at boot.\n */\nexport function getRenownWorkerSignerSpec(\n renown: IRenown,\n keypairPath?: string,\n): FactorySpec {\n const { signer } = renown;\n const user = signer.user;\n return {\n module: {\n filePath: createRequire(import.meta.url).resolve(\"@renown/sdk/node\"),\n exportName: \"createNodeRenownSigner\",\n },\n initArgs: {\n appName: signer.app?.name ?? \"switchboard\",\n keypairPath: resolve(keypairPath ?? DEFAULT_KEYPAIR_PATH),\n ...(signer.app?.key ? { did: signer.app.key } : {}),\n ...(user\n ? {\n user: {\n address: user.address,\n networkId: user.networkId,\n chainId: user.chainId,\n },\n }\n : {}),\n },\n };\n}\n\n/** Where switchboard reads the credentials binding keys to wallets. */\nexport type RenownTrustSource =\n | { source: \"remote\"; renownUrl?: string; switchboardUrl?: string }\n | { source: \"self\"; request: SwitchboardRequestFn };\n\n/**\n * Admits a key as a signer for an address a Renown credential binds it to; a\n * `self` source has no worker spec. In process, the switchboard's own key is\n * matched against its current user; the worker spec carries the user known now.\n */\nexport async function getRenownTrustPolicyConfig(\n trustSource: RenownTrustSource,\n renown: IRenown | null,\n): Promise<Pick<SignerConfig, \"trustPolicy\" | \"workerTrustPolicy\">> {\n const ownSigner = renown?.signer;\n if (trustSource.source === \"self\") {\n return {\n trustPolicy: createRenownTrustPolicy({\n switchboard: trustSource.request,\n ownSigner,\n }),\n };\n }\n\n const switchboardUrl = await resolveSwitchboardEndpoint({\n switchboardUrl: trustSource.switchboardUrl,\n baseUrl: trustSource.renownUrl,\n });\n const options = {\n ...(switchboardUrl ? { switchboard: switchboardUrl } : {}),\n ...(trustSource.renownUrl ? { renownUrl: trustSource.renownUrl } : {}),\n } satisfies RenownTrustPolicyOptions;\n const self = ownIdentity(renown);\n return {\n trustPolicy: createRenownTrustPolicy({ ...options, ownSigner }),\n workerTrustPolicy: {\n module: {\n filePath: createRequire(import.meta.url).resolve(\"@renown/sdk/node\"),\n exportName: \"createRenownTrustPolicy\",\n },\n initArgs: { ...options, ...(self ? { self } : {}) },\n },\n };\n}\n\nfunction ownIdentity(\n renown: IRenown | null,\n): RenownTrustPolicyOptions[\"self\"] | undefined {\n const key = renown?.signer.app?.key;\n if (!key) {\n return undefined;\n }\n const user = renown.signer.user;\n return {\n key,\n user: {\n address: user?.address ?? \"\",\n networkId: user?.networkId ?? \"\",\n chainId: user?.chainId ?? 0,\n },\n };\n}\n","import type {\n UnsupportedStoredDocuments,\n UnsupportedStoredProtocolError,\n} from \"@powerhousedao/reactor\";\n\nconst MODES: readonly UnsupportedStoredDocuments[] = [\"refuse\", \"read-only\"];\n\n/** From REACTOR_UNSUPPORTED_STORED_DOCUMENTS; `input` wins when defined. */\nexport function resolveUnsupportedStoredDocuments(\n input: UnsupportedStoredDocuments | undefined,\n env: NodeJS.ProcessEnv,\n): UnsupportedStoredDocuments {\n if (input !== undefined) return input;\n const raw = env.REACTOR_UNSUPPORTED_STORED_DOCUMENTS?.trim();\n if (!raw) return \"refuse\";\n if (!(MODES as readonly string[]).includes(raw)) {\n throw new Error(\n `REACTOR_UNSUPPORTED_STORED_DOCUMENTS must be \"refuse\" or \"read-only\", got \"${raw}\"`,\n );\n }\n return raw as UnsupportedStoredDocuments;\n}\n\n/** The reactor refused to start over documents this build does not run. */\nexport class StoredDocumentsRefusedError extends Error {\n readonly versions: readonly { protocol: string; version: number }[];\n readonly documents: number;\n\n constructor(cause: UnsupportedStoredProtocolError) {\n const named = cause.versions\n .map(({ protocol, version }) => `${protocol} ${version}`)\n .join(\", \");\n super(\n `Refusing to start: ${cause.documents} stored document(s) require ${named}, which this switchboard does not run. ` +\n `Either start a switchboard build that runs ${named}, or set REACTOR_UNSUPPORTED_STORED_DOCUMENTS=read-only to start with those documents read-only.`,\n { cause },\n );\n this.name = \"StoredDocumentsRefusedError\";\n this.versions = cause.versions;\n this.documents = cause.documents;\n }\n\n static isError(error: unknown): error is StoredDocumentsRefusedError {\n return Error.isError(error) && error.name === \"StoredDocumentsRefusedError\";\n }\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * One process per PGlite store. PGlite is an in-process Postgres with no\n * postmaster to arbitrate: two processes opening the same data dir are two\n * writers on one PGDATA, which tears the store (it then aborts at the next\n * checkpoint or refuses to reopen). Hosts share one `.ph` tree by design\n * (`ph run vetra`, `ph run cli`, `ph run desktop`, classic `ph vetra` /\n * `ph switchboard` all use `.ph/reactor-storage` + `.ph/read-storage`), and the\n * per-host run records cannot see each other — so the guard lives here,\n * below every host: the switchboard takes a lock per store dir before\n * opening it.\n *\n * The lock is a SIBLING file (`<dir>.lock`), not a file inside the data dir:\n * initdb refuses a non-empty directory. A lock whose owner is dead (a\n * hard-killed process) is stale and taken over; the owner releases it on\n * exit. The same process may re-acquire its own lock (in-process restarts).\n */\nexport interface StoreLockOwner {\n pid: number;\n startedAt: string;\n command: string;\n}\n\nexport class StoreInUseError extends Error {\n constructor(\n readonly dir: string,\n readonly owner: StoreLockOwner,\n ) {\n super(\n `The PGlite store ${dir} is in use by another process (pid ${owner.pid}, since ${owner.startedAt}: ${owner.command}). ` +\n \"Two processes on one PGlite store corrupt it. Stop that process first, or point this one at a different store.\",\n );\n this.name = \"StoreInUseError\";\n }\n}\n\nconst lockPathOf = (dir: string) => `${path.resolve(dir)}.lock`;\n\nfunction isAlive(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\nfunction readOwner(file: string): StoreLockOwner | undefined {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf8\")) as StoreLockOwner;\n } catch {\n return undefined;\n }\n}\n\nconst held = new Set<string>();\nlet exitHookInstalled = false;\n\nfunction releaseAll(): void {\n for (const file of held) {\n const owner = readOwner(file);\n if (owner?.pid === process.pid) {\n try {\n fs.rmSync(file);\n } catch {\n // already gone\n }\n }\n }\n held.clear();\n}\n\n/** Take the lock for each store dir, or throw StoreInUseError naming the\n * live owner. Idempotent within one process. */\nexport function acquireStoreLocks(\n dirs: readonly string[],\n isPidAlive: (pid: number) => boolean = isAlive,\n): void {\n const mine: StoreLockOwner = {\n pid: process.pid,\n startedAt: new Date().toISOString(),\n command: process.argv.slice(1).join(\" \").slice(0, 200),\n };\n for (const dir of new Set(dirs.map((d) => path.resolve(d)))) {\n const file = lockPathOf(dir);\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const owner = readOwner(file);\n if (owner && owner.pid !== process.pid && isPidAlive(owner.pid)) {\n throw new StoreInUseError(dir, owner);\n }\n // free, stale (dead owner) or already ours: write our claim\n fs.writeFileSync(file, `${JSON.stringify(mine)}\\n`);\n held.add(file);\n }\n if (!exitHookInstalled) {\n exitHookInstalled = true;\n process.on(\"exit\", releaseAll);\n }\n}\n\n/** Release this process's store locks (tests; orderly shutdown). */\nexport function releaseStoreLocks(): void {\n releaseAll();\n}\n","#!/usr/bin/env node\nimport { metrics, trace } from \"@opentelemetry/api\";\nimport { getConfig } from \"@powerhousedao/config/node\";\nimport { ReactorInstrumentation } from \"@powerhousedao/opentelemetry-instrumentation-reactor\";\nimport {\n CatchUpPriority,\n DriveCollectionId,\n EventBus,\n IN_MEMORY_PGLITE_STORAGE_FACTS,\n PGLITE_PATH_STORAGE_FACTS,\n POSTGRES_STORAGE_FACTS,\n REACTOR_SCHEMA,\n ReactorBuilder,\n ReactorClientBuilder,\n createHybridProjectionCoordinatorFactory,\n instrumentPgPool,\n parseCatchUpPriority,\n parseDriveUrl,\n type CatchUpPrioritySetting,\n type Database,\n type InProcessReactorClientModule,\n type JwtHandler,\n type PoolInstrumentation,\n type ReactorStorageFacts,\n UnsupportedStoredProtocolError,\n} from \"@powerhousedao/reactor\";\nimport {\n HttpPackageLoader,\n ImportPackageLoader,\n PackageManagementService,\n PackagesSubgraph,\n initializeAndStartAPI,\n NodeEventLoopDelay,\n RequestLoadRecorder,\n reportFailure,\n resolveRenownConfig,\n runDetached,\n type CanonicalDocumentId,\n type ClientInitializerDependencies,\n type CredentialVerifier,\n type IPackageLoader,\n type PgliteFactory,\n type ResolvedRenownConfig,\n} from \"@powerhousedao/reactor-api\";\nimport { httpsHooksPath } from \"@powerhousedao/reactor-api/https-hooks\";\nimport { ThreadedPGlite } from \"@powerhousedao/reactor-api/pglite-node\";\nimport type { VitePackageLoader } from \"@powerhousedao/reactor-api/vite\";\nimport { createRemoteAttachmentService } from \"@powerhousedao/reactor-attachments\";\nimport { createAttachmentClient } from \"@powerhousedao/reactor-attachments/client\";\nimport {\n DriveNodeView,\n NodeProcessor,\n ReactorDriveClient,\n type ReactorDriveDatabase,\n} from \"@powerhousedao/reactor-drive\";\nimport {\n createReactorDriveResolvers,\n REACTOR_DRIVE_SUBGRAPH_NAME,\n reactorDriveSubgraphTypeDefs,\n} from \"@powerhousedao/reactor-drive/subgraph\";\nimport type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport {\n createLocalCredentialVerifier,\n RENOWN_READ_MODEL_SUBGRAPH,\n type CredentialCheck,\n type IRenown,\n type SwitchboardRequestFn,\n} from \"@renown/sdk/node\";\nimport * as Sentry from \"@sentry/node\";\nimport { childLogger, setLogLevel, type ILogger } from \"document-model\";\nimport dotenv from \"dotenv\";\nimport { Kysely, PostgresDialect } from \"kysely\";\nimport { register } from \"node:module\";\nimport type http from \"node:http\";\nimport net from \"node:net\";\nimport path from \"path\";\nimport { Pool } from \"pg\";\nimport type { ViteDevServer } from \"vite\";\nimport { registerAttachmentRoutes } from \"./attachments/index.js\";\nimport {\n registerAttachmentReferenceReadModel,\n registerAttachmentReferenceReadModelOnModule,\n} from \"./attachment-reference-read-model.mjs\";\nimport { installFatalErrorShutdown } from \"./fatal-shutdown.mjs\";\nimport {\n resolvePrivacy,\n startPrivacy,\n type ResolvedPrivacy,\n type RunningPrivacy,\n} from \"./privacy.mjs\";\nimport { applySwitchboardReactorDefaults } from \"./builder-defaults.mjs\";\nimport {\n createSwitchboardPluginHost,\n isPluginHostEnabled,\n type SwitchboardPluginHost,\n} from \"./plugin-host.mjs\";\nimport {\n assertProjectionWorkerSupported,\n resolveProjectionWorkerOptions,\n} from \"./projection-worker.mjs\";\nimport {\n buildWorkerDbConfig,\n resolveHostPoolSize,\n keepImportableSources,\n resolveWorkerModelSources,\n resolveWorkerPoolOptions,\n} from \"./worker-pool.mjs\";\nimport { inspectionThrottleFromEnv } from \"./inspection-throttle.mjs\";\nimport { initProfilerFromEnv } from \"./profiler.js\";\nimport { initFeatureFlags } from \"./feature-flags.js\";\nimport { resolveInspectionEnabled } from \"./inspection-flag.mjs\";\nimport { resolveMcpEnabled } from \"./mcp-flag.mjs\";\nimport {\n WORKFLOW_PACKAGE_NAME,\n WORKFLOW_TELEMETRY_SCOPE,\n composeWorkflowRuntime,\n modelManifestSource,\n assertWorkflowPackageLoadable,\n isWorkflowSingletonConflict,\n resolveWorkflowsEnabled,\n retryWorkflowSingleton,\n workflowSingletonLossHandler,\n type WorkflowSingletonRetry,\n type ComposedWorkflowRuntime,\n type ModelManifestSource,\n} from \"./workflow-runtime.mjs\";\nimport {\n ClosablePGliteDialect,\n reactorPgliteDialectOptions,\n} from \"./pglite-dialect.js\";\nimport { runPglitePreflight } from \"./pglite-preflight.js\";\nimport {\n createPgliteStoreFactory,\n resolvePgliteWorkersEnabled,\n terminateOnPoisoned,\n} from \"./pglite-store.mjs\";\nimport {\n CURRENT_PG_MAJOR,\n isSupportedMajor,\n type SupportedPgMajor,\n} from \"./pglite-version.js\";\nimport { resolveReactorFeatureFlags } from \"./reactor-feature-flags.mjs\";\nimport { resolveCreateSignaturePolicy } from \"./create-signature-policy.mjs\";\nimport { reactorDbUrlOf, workerPoolIssues } from \"./boot-preconditions.mjs\";\nimport {\n getRenownSignerConfig,\n getRenownTrustPolicyConfig,\n initRenown,\n} from \"./renown.js\";\nimport type { StartServerOptions, SwitchboardReactor } from \"./types.js\";\nimport {\n StoredDocumentsRefusedError,\n resolveUnsupportedStoredDocuments,\n} from \"./unsupported-stored-documents.mjs\";\nimport {\n addDefaultDrive,\n addDefaultReactorDrive,\n isPostgresUrl,\n} from \"./utils.mjs\";\nimport { acquireStoreLocks } from \"./store-lock.mjs\";\nimport {\n defaultStoreDirs,\n resolvePhDir,\n} from \"@powerhousedao/shared/clis/ph-dir\";\nimport { isDotenvDisabled } from \"@powerhousedao/shared/clis/project-env\";\n\nconst defaultLogger = childLogger([\"switchboard\"]);\n\nconst LogLevel = (process.env.LOG_LEVEL as ILogger[\"level\"] | \"\") || \"info\";\nsetLogLevel(LogLevel);\n\nif (!isDotenvDisabled()) dotenv.config();\n\n// Feature flag constants\nconst DOCUMENT_MODEL_SUBGRAPHS_ENABLED = \"DOCUMENT_MODEL_SUBGRAPHS_ENABLED\";\nconst DOCUMENT_MODEL_SUBGRAPHS_ENABLED_DEFAULT = true;\n\nconst DEFAULT_PORT = process.env.PORT ? Number(process.env.PORT) : 4001;\n\n// How many ports forward from the requested one we will try before giving up.\nconst PORT_FALLBACK_ATTEMPTS = 20;\n\n// Retired with the snapshot store; PGlite writes through NodeFS now.\nlet flushIntervalWarned = false;\nfunction warnIgnoredFlushInterval(logger: ILogger): void {\n if (flushIntervalWarned) return;\n if (process.env.PGLITE_FLUSH_INTERVAL_MS === undefined) return;\n flushIntervalWarned = true;\n logger.warn(\n \"PGLITE_FLUSH_INTERVAL_MS is set but ignored: PGlite stores no longer snapshot on a timer.\",\n );\n}\n\n// When set, runs both reactor and read-model PGLite instances purely in-memory.\nconst PGLITE_IN_MEMORY = process.env.PH_PGLITE_IN_MEMORY === \"1\";\n\n/**\n * Attempt to bind a throwaway TCP server to the given port. Resolves true if\n * the port is free, false if the OS reports it in use. Any other error is\n * surfaced so we don't silently mask real issues (permissions, bad host, …).\n */\nexport async function isPortAvailable(port: number): Promise<boolean> {\n try {\n // `::` is dual-stack on most systems, so it sees IPv6 and IPv4 listeners.\n return await probePort(port, \"::\");\n } catch (error) {\n // A host without IPv6, e.g. a container, can only probe IPv4.\n if (!isNoIpv6Error(error)) throw portProbeError(port, error);\n try {\n return await probePort(port, \"0.0.0.0\");\n } catch (ipv4Error) {\n throw portProbeError(port, ipv4Error);\n }\n }\n}\n\nconst isNoIpv6Error = (error: unknown) =>\n [\"EAFNOSUPPORT\", \"EADDRNOTAVAIL\"].includes(\n (error as NodeJS.ErrnoException).code ?? \"\",\n );\n\nconst portProbeError = (port: number, error: unknown) =>\n new Error(\n `Could not check whether port ${port} is free: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n\nfunction probePort(port: number, host: string): Promise<boolean> {\n return new Promise((resolve, reject) => {\n const tester = net.createServer();\n tester.once(\"error\", (err: NodeJS.ErrnoException) => {\n if (err.code === \"EADDRINUSE\" || err.code === \"EACCES\") {\n resolve(false);\n } else {\n reject(err);\n }\n });\n tester.once(\"listening\", () => {\n tester.close(() => resolve(true));\n });\n tester.listen({ port, host });\n });\n}\n\n/** The powerhouse.config.json this run reads, defaulting to the cwd copy. */\nfunction resolveConfigPath(configFile: string | undefined): string {\n return configFile ?? path.join(process.cwd(), \"powerhouse.config.json\");\n}\n\n// An unreadable config file means \"not configured\", not a boot failure:\n// workflows are opt-in.\nfunction readConfigWorkflowsEnabled(configPath: string): boolean {\n try {\n return getConfig(configPath).workflows?.enabled ?? false;\n } catch {\n return false;\n }\n}\n\nasync function resolveServerPort(\n requested: number,\n strictPort: boolean,\n logger: ILogger,\n): Promise<number> {\n if (strictPort) return requested;\n for (let i = 0; i < PORT_FALLBACK_ATTEMPTS; i++) {\n const candidate = requested + i;\n if (await isPortAvailable(candidate)) {\n if (candidate !== requested) {\n logger.info(\n `Port ${requested} is in use. Falling back to port ${candidate}.`,\n );\n }\n return candidate;\n }\n }\n // Couldn't find a free port in the window; let the caller surface the\n // original EADDRINUSE when the real bind attempts runs.\n return requested;\n}\n\n/**\n * The reactor's storage handle, plus the pool instrumentation when that\n * storage is Postgres. The PGlite branch has no `pg.Pool` at all, so the\n * instrumentation is absent rather than optional-by-convention.\n */\ntype ReactorStorage = {\n kysely: Kysely<Database>;\n poolInstrumentation: PoolInstrumentation | undefined;\n storageFacts: ReactorStorageFacts;\n};\n\nexport async function createReactorKysely(opts: {\n reactorDbUrl: string | undefined;\n reactorPgliteDir: string | null;\n reactorPgliteMajor: SupportedPgMajor | null;\n inMemory: boolean;\n /**\n * Resolved lazily: only the Postgres branch has a host pool, and\n * {@link resolveHostPoolSize} throws on a bad REACTOR_DB_POOL_SIZE_HOST.\n * Called eagerly it would fail a PGlite-backed server over a value that\n * path never reads.\n */\n hostPoolSize: () => number;\n /** Open the PGlite store in its own worker thread. */\n pgliteWorkers: boolean;\n logger: ILogger;\n}): Promise<ReactorStorage> {\n const {\n reactorDbUrl,\n reactorPgliteDir,\n reactorPgliteMajor,\n inMemory,\n hostPoolSize,\n pgliteWorkers,\n logger,\n } = opts;\n\n if (reactorDbUrl && isPostgresUrl(reactorDbUrl)) {\n const connectionString = reactorDbUrl.includes(\"?\")\n ? reactorDbUrl\n : `${reactorDbUrl}?sslmode=disable`;\n const poolSize = hostPoolSize();\n const pool = new Pool({ connectionString, max: poolSize });\n // Named to match the reactor's own convention for the pools it opens\n // itself (`reactor-worker-N`, `projection-shard-N`).\n const poolInstrumentation = instrumentPgPool(pool, \"reactor-host\");\n logger.info(\n `Using PostgreSQL for reactor storage (host pool max ${poolSize})`,\n );\n return {\n kysely: new Kysely<Database>({ dialect: new PostgresDialect({ pool }) }),\n poolInstrumentation,\n storageFacts: POSTGRES_STORAGE_FACTS,\n };\n }\n\n if (!reactorPgliteDir || reactorPgliteMajor === null) {\n throw new Error(\"Reactor PGLite directory not resolved\");\n }\n const openStore = await createPgliteStoreFactory({\n label: \"reactor-storage\",\n major: reactorPgliteMajor,\n parsers: \"none\",\n inMemory,\n threaded: pgliteWorkers,\n logger,\n });\n const pglite = openStore(reactorPgliteDir);\n const dialectOptions =\n pglite instanceof ThreadedPGlite\n ? terminateOnPoisoned(reactorPgliteDialectOptions(logger), pglite)\n : reactorPgliteDialectOptions(logger);\n return {\n kysely: new Kysely<Database>({\n dialect: new ClosablePGliteDialect(pglite, dialectOptions),\n }),\n poolInstrumentation: undefined,\n storageFacts: inMemory\n ? IN_MEMORY_PGLITE_STORAGE_FACTS\n : PGLITE_PATH_STORAGE_FACTS,\n };\n}\n\nexport interface PgliteStorageDirs {\n /** Read-model store: a Postgres URL or a PGlite dir. */\n readModelPath: string;\n /** Reactor store: a Postgres URL or a PGlite dir. */\n reactorPath: string;\n /** PGlite dir for the reactor, null for Postgres or a caller-owned reactor. */\n reactorPgliteDir: string | null;\n /** PGlite dir for the read model, null for Postgres. */\n readModelPgliteDir: string | null;\n /** The PGlite dirs for the pre-flight, as before (not deduplicated). */\n pgliteDirs: string[];\n /** Set when BOTH stores are PGlite on one dir (see resolvePgliteStorageDirs). */\n sharedPgliteDir: string | null;\n}\n\n/**\n * Where the two stores live — the classic resolution, relocated verbatim.\n * Classic layout: `./.ph/reactor-storage` for the reactor and\n * `.ph/read-storage` for the read model (the same names inside\n * `${userData}/.ph` under a shell's PH_USER_DATA_DIR). `dbPath` also names\n * the reactor store unless PH_REACTOR_DATABASE_URL does: with `dbPath` alone\n * both stores share one location. That is the long-standing contract of\n * `--db-path` and fine for one Postgres database, but for PGlite it is two\n * postmasters on one data dir — reported via `sharedPgliteDir` so the caller\n * warns. Not refused: changing that contract is a separate decision.\n */\nexport function resolvePgliteStorageDirs(opts: {\n dbPath: string | undefined;\n reactorDbUrl: string | undefined;\n /** The caller passed its own reactor — the reactor-side dir is unused. */\n callerReactor: boolean;\n phDir?: string;\n}): PgliteStorageDirs {\n const { dbPath, reactorDbUrl, callerReactor } = opts;\n const defaults = defaultStoreDirs(process.env, opts.phDir);\n const readModelPath = dbPath || defaults.readModel;\n const reactorPath = reactorDbUrl || defaults.reactor;\n const reactorPgliteDir = callerReactor\n ? null\n : !reactorDbUrl || !isPostgresUrl(reactorDbUrl)\n ? reactorPath\n : null;\n const readModelPgliteDir =\n !dbPath || !isPostgresUrl(dbPath) ? readModelPath : null;\n const sharedPgliteDir =\n reactorPgliteDir !== null &&\n readModelPgliteDir !== null &&\n path.resolve(reactorPgliteDir) === path.resolve(readModelPgliteDir)\n ? path.resolve(reactorPgliteDir)\n : null;\n const pgliteDirs = [reactorPgliteDir, readModelPgliteDir].filter(\n (d): d is string => d !== null,\n );\n return {\n readModelPath,\n reactorPath,\n reactorPgliteDir,\n readModelPgliteDir,\n pgliteDirs,\n sharedPgliteDir,\n };\n}\n\n/** Derive the remote attachment service config for switchboard's own `/attachments/*` API. */\nexport function deriveAttachmentServiceConfig(\n options: Pick<StartServerOptions, \"attachmentServiceUrl\" | \"https\">,\n serverPort: number,\n renown: IRenown | null,\n): { remoteUrl: string; jwtHandler: JwtHandler | undefined } {\n const protocol = options.https ? \"https\" : \"http\";\n const remoteUrl =\n options.attachmentServiceUrl ??\n process.env.PH_SWITCHBOARD_PUBLIC_URL ??\n `${protocol}://localhost:${serverPort}`;\n const jwtHandler: JwtHandler | undefined = renown\n ? async (url: string) =>\n renown.user\n ? renown.getBearerToken({ expiresIn: 10, aud: url })\n : undefined\n : undefined;\n return { remoteUrl, jwtHandler };\n}\n\nasync function initServer(\n serverPort: number,\n options: StartServerOptions,\n renown: IRenown | null,\n renownConfig: ResolvedRenownConfig,\n) {\n const {\n dev,\n packages = [],\n remoteDrives = [],\n logger = defaultLogger,\n } = options;\n\n // R2 plugin pipeline (FEATURE_PLUGIN_HOST_ENABLED): flag off, the inline\n // path below runs byte-identically; flag on, carved subsystems run as\n // built-in plugins through the hook moments marked along this function.\n const pluginHost: SwitchboardPluginHost | null = isPluginHostEnabled()\n ? createSwitchboardPluginHost(\n {\n logger,\n options: options as unknown as Record<string, unknown>,\n renown,\n },\n options.pluginComposition,\n )\n : null;\n if (pluginHost) {\n options = await pluginHost.transformOptions(options);\n // Presence is activation: whatever no plugin (or explicit option) set\n // stays OFF. The mcp/workflows plugins set these true at\n // transformServerOptions; their absence must actually deactivate.\n options.mcp ??= false;\n options.workflows = { enabled: options.workflows?.enabled === true };\n }\n logger.level = LogLevel;\n const dbPath =\n options.dbPath ??\n process.env.DATABASE_URL ??\n process.env.PH_SWITCHBOARD_DATABASE_URL;\n\n const reactorDbUrl = reactorDbUrlOf(options.dbPath, process.env);\n // Postgres URLs or local PGlite dirs under the project's .ph tree. When\n // the caller passes in a reactor, the reactor-side PGLite dir is unused —\n // the caller owns its own storage. Only the read-model dir is still needed\n // by reactor-api itself. Refuses one PGlite dir for both stores.\n const {\n readModelPath,\n reactorPgliteDir,\n readModelPgliteDir,\n pgliteDirs,\n sharedPgliteDir,\n } = resolvePgliteStorageDirs({\n dbPath,\n reactorDbUrl,\n callerReactor: options.reactor !== undefined,\n });\n if (sharedPgliteDir !== null) {\n logger.warn(\n `The reactor and read-model PGlite stores share one directory (${sharedPgliteDir}): ` +\n \"two PGlite instances on one data dir can abort at the first checkpoint and leave the store unopenable. \" +\n \"Set PH_REACTOR_DATABASE_URL to a separate directory, or leave dbPath unset for the classic \" +\n \"./.ph/reactor-storage + .ph/read-storage layout.\",\n );\n }\n\n // PGLite pre-flight: convert legacy single-file snapshot stores, clear\n // stale lock and WAL temp files, then detect PG_VERSION and migrate or\n // warn. Under PH_FORCE_PG_VERSION the dirs are wiped instead.\n // One process per PGlite store, before anything (the pre-flight included)\n // touches it: hosts share one .ph tree, so a second `ph run …` / `ph vetra`\n // in the same project must fail here instead of tearing the store.\n if (!PGLITE_IN_MEMORY) acquireStoreLocks(pgliteDirs);\n warnIgnoredFlushInterval(logger);\n const detectedMajors = await runPglitePreflight({\n dirs: pgliteDirs,\n forcePgVersion: options.forcePgVersion,\n migratePglite: options.migratePglite,\n inMemory: PGLITE_IN_MEMORY,\n logger,\n });\n\n function resolvePgliteMajorForDir(dir: string): SupportedPgMajor {\n if (options.forcePgVersion !== undefined) return options.forcePgVersion;\n const detected = detectedMajors.get(dir);\n if (detected === undefined) return CURRENT_PG_MAJOR;\n if (!isSupportedMajor(detected)) {\n throw new Error(\n `Unsupported PGLite data dir at ${dir}: PG_VERSION=${detected}`,\n );\n }\n return detected;\n }\n\n const reactorPgliteMajor = reactorPgliteDir\n ? resolvePgliteMajorForDir(reactorPgliteDir)\n : null;\n const readModelPgliteMajor = readModelPgliteDir\n ? resolvePgliteMajorForDir(readModelPgliteDir)\n : null;\n\n const inspectionThrottle = inspectionThrottleFromEnv(process.env);\n let workerPool = resolveWorkerPoolOptions(options.workerPool, process.env);\n if (workerPool && options.reactor) {\n logger.warn(\n \"Worker pool configuration ignored: the caller-provided reactor owns its own executor\",\n );\n workerPool = null;\n }\n if (workerPool) {\n const issue = workerPoolIssues({\n dev: dev === true,\n workers: workerPool.numWorkers,\n projectionWorker: false,\n reactorDbUrl,\n authEnforcement:\n resolveReactorFeatureFlags(process.env).flags.authEnforcement === true,\n renownSource: renownConfig.source,\n }).at(0);\n if (issue) throw new Error(issue);\n }\n\n const unsupportedStoredDocuments = resolveUnsupportedStoredDocuments(\n options.unsupportedStoredDocuments,\n process.env,\n );\n\n let projectionWorker = resolveProjectionWorkerOptions(\n options.projectionWorker,\n process.env,\n );\n if (projectionWorker && options.reactor) {\n logger.warn(\n \"Projection worker configuration ignored: the caller-provided reactor owns its own read-model coordinator\",\n );\n projectionWorker = null;\n }\n if (projectionWorker) {\n assertProjectionWorkerSupported({ dev: dev === true, reactorDbUrl });\n }\n\n // The reactor-api owns its own PGlite/HTTP/WS resources but has no shutdown\n // path of its own; we register `api.dispose` as a reactor shutdown hook so\n // those resources drain inside the reactor's SIGINT chain. The reference\n // is forward — `initializeClient` runs (and registers the hook) before\n // `initializeAndStartAPI` returns the api — so the closure reads `apiRef`\n // at hook-fire time, not at registration time.\n const apiRef: { current: { dispose: () => Promise<void> } | undefined } = {\n current: undefined,\n };\n let driveNodeView: DriveNodeView | undefined;\n\n // HTTP registry package loading\n const configPath = resolveConfigPath(options.configFile);\n const config = getConfig(configPath);\n const registryUrl =\n options.registryUrl ??\n process.env.PH_REGISTRY_URL ??\n config.packageRegistryUrl;\n const registryPackages = process.env.PH_REGISTRY_PACKAGES;\n const dynamicModelLoading =\n options.dynamicModelLoading ?? process.env.DYNAMIC_MODEL_LOADING === \"true\";\n let httpLoader: HttpPackageLoader | undefined;\n\n if (registryUrl) {\n // Register HTTP/HTTPS module loader hooks for dynamic package imports\n register(httpsHooksPath, import.meta.url);\n httpLoader = new HttpPackageLoader({ registryUrl });\n registryPackages?.split(\",\").forEach((p) => {\n const name = p.trim();\n if (!packages.includes(name)) {\n packages.push(name);\n }\n });\n }\n\n // Registry packages import from the on-disk cache, which workers can read.\n const registryPackageNames = new Set(\n (registryPackages ?? \"\")\n .split(\",\")\n .map((p) => p.trim())\n .filter(Boolean),\n );\n const resolveRegistryModels = async (\n identifier: string,\n ): Promise<string | null> =>\n httpLoader && registryPackageNames.has(identifier)\n ? ((await httpLoader.cachePackage(identifier)).entries.documentModels ??\n null)\n : null;\n\n const reactorLogger = logger.child([\"reactor\"]);\n // Latched: dropWriteReady reports the fatal once per dropped job.\n let projectionWorkerFatalFired = false;\n const onProjectionWorkerFatal = (shardId: string, reason: Error) => {\n if (projectionWorkerFatalFired) {\n return;\n }\n projectionWorkerFatalFired = true;\n reactorLogger.error(\n `Projection worker ${shardId} died; shutting down so the supervisor restarts a healthy process`,\n reason,\n );\n // SIGTERM takes the builder's withSignalHandlers() path: kill, hooks, db.\n process.kill(process.pid, \"SIGTERM\");\n };\n // Resolved in startSwitchboard, which owns the flag mechanism; initServer\n // only reads the answer.\n const workflowsEnabled = options.workflows?.enabled === true;\n // Resolved before the reactor is built: a bad secret fails the boot early.\n // Flag-on, the privacy plugin owns this resolve (same fail-fast timing, in\n // transformServerOptions above).\n const privacyConfig = pluginHost\n ? ({ enabled: false } as ResolvedPrivacy)\n : resolvePrivacy(options.privacy, process.env);\n\n // Through the package manager like any other, so one route carries the\n // models, the subgraphs and the piece.\n if (workflowsEnabled) {\n await assertWorkflowPackageLoadable();\n if (!packages.includes(WORKFLOW_PACKAGE_NAME)) {\n packages.push(WORKFLOW_PACKAGE_NAME);\n }\n }\n\n // Set only when we build the reactor ourselves; a caller-provided one keeps\n // its own lifecycle and must not be torn down here.\n let ownedReactorModule: InProcessReactorClientModule | undefined;\n // Paces an owned reactor's processor backfills; fed by this server's load.\n const catchUpPriority = new CatchUpPriority(\n catchUpPrioritySettingFromEnv(process.env.PH_CATCH_UP_PRIORITY, logger),\n );\n // The models workers and workflow pieces import; only on a reactor built here.\n let workerModels: ModelManifestSource | undefined;\n // Bound once the api serves the renown read model; see `localCredentialCheck`.\n let localRenownRequest: SwitchboardRequestFn | undefined;\n const initializeClient = async (\n documentModels: DocumentModelModule[],\n {\n attachmentReferenceWriter,\n upgradeManifests,\n }: ClientInitializerDependencies,\n ) => {\n // When the caller hands us a pre-built reactor module, reuse it\n // instead of constructing one. The caller owns the reactor lifecycle\n // and must call `switchboard.shutdown()` from their own teardown to\n // drain /graphql, MCP, attachments, etc.\n if (options.reactor) {\n const attachmentReferenceProjection =\n await registerAttachmentReferenceReadModelOnModule(\n options.reactor,\n attachmentReferenceWriter,\n );\n if (options.reactor.reactorModule) {\n const instrumentation = new ReactorInstrumentation(\n options.reactor.reactorModule,\n );\n instrumentation.start();\n reactorLogger.info(\n \"Reactor metrics instrumentation started (using caller-provided reactor)\",\n );\n }\n return {\n module: options.reactor,\n attachmentReferenceProjection,\n };\n }\n\n const {\n kysely: baseKysely,\n poolInstrumentation,\n storageFacts,\n } = await createReactorKysely({\n reactorDbUrl,\n reactorPgliteDir,\n reactorPgliteMajor,\n inMemory: PGLITE_IN_MEMORY,\n hostPoolSize: () => resolveHostPoolSize(process.env),\n pgliteWorkers: options.pgliteWorkers === true,\n logger,\n });\n\n const maxSkipThreshold = parseInt(process.env.MAX_SKIP_THRESHOLD ?? \"\", 10);\n const hasSkipThreshold = !isNaN(maxSkipThreshold) && maxSkipThreshold > 0;\n if (hasSkipThreshold) {\n logger.info(`Reactor maxSkipThreshold set to ${maxSkipThreshold}`);\n }\n\n // Flip these per document-sharing fleet, never per node: replay decisions\n // are consensus outcomes, so nodes that disagree on the flags diverge.\n const { flags: reactorFeatureFlags, enabled: enabledFeatureFlags } =\n resolveReactorFeatureFlags(process.env);\n if (enabledFeatureFlags.length > 0) {\n logger.info(\n `Reactor feature flags enabled: ${enabledFeatureFlags.join(\", \")}`,\n );\n }\n\n const reactorBuilder = new ReactorBuilder()\n .withEventBus(new EventBus())\n .withKysely(baseKysely)\n .withStorageFacts(storageFacts)\n .withFeatures({\n legacyProcessorIds:\n process.env.REACTOR_LEGACY_PROCESSOR_IDS !== \"false\",\n })\n .withUnsupportedStoredDocuments(unsupportedStoredDocuments)\n .withCatchUpPriority(catchUpPriority);\n\n // Feeds `module.pools`, which ReactorInstrumentation reads to emit\n // reactor.db.pool.{acquire.wait_duration,size,idle,waiting}. Without this\n // the host pool is the one pool the reactor opens that nobody can see.\n // Note the gauges observe pg-pool only: behind a transaction-mode\n // pgbouncer, `waiting` can read 0 while requests queue in the pooler.\n if (poolInstrumentation) {\n reactorBuilder.withInstrumentedPool(poolInstrumentation);\n }\n\n const clientBuilder = new ReactorClientBuilder().withReactorBuilder(\n reactorBuilder,\n );\n\n // Subpath import keeps vetra's React editors out of the node bundle.\n const vetraDocumentModels: DocumentModelModule[] = dev\n ? (\n Object.values(\n await import(\"@powerhousedao/vetra/document-models\"),\n ) as unknown[]\n ).filter(\n (m): m is DocumentModelModule =>\n typeof m === \"object\" &&\n m !== null &&\n \"documentModel\" in m &&\n \"reducer\" in m,\n )\n : [];\n\n applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, {\n signalHandlers: options.signalHandlers,\n documentModels: [...documentModels, ...vetraDocumentModels],\n upgradeManifests,\n executorConfig:\n hasSkipThreshold || enabledFeatureFlags.length > 0\n ? {\n ...(hasSkipThreshold ? { maxSkipThreshold } : {}),\n ...(enabledFeatureFlags.length > 0\n ? { featureFlags: reactorFeatureFlags }\n : {}),\n }\n : undefined,\n documentModelLoader:\n httpLoader && dynamicModelLoading\n ? httpLoader.documentModelLoader\n : undefined,\n logger: reactorLogger,\n signer: renown\n ? getRenownSignerConfig(renown, options.identity?.keypairPath)\n : undefined,\n createSignaturePolicy: resolveCreateSignaturePolicy(process.env, {\n hasSigner: renown !== null,\n logger,\n }),\n trustPolicy: reactorFeatureFlags.authEnforcement\n ? await getRenownTrustPolicyConfig(\n renownConfig.source === \"self\"\n ? {\n source: \"self\",\n request: (query, variables) =>\n localRenownRequest\n ? localRenownRequest(query, variables)\n : Promise.reject(\n new Error(\n \"The local renown read model is not bound yet\",\n ),\n ),\n }\n : {\n source: \"remote\",\n renownUrl: renownConfig.url,\n switchboardUrl: renownConfig.switchboardUrl,\n },\n renown,\n )\n : undefined,\n });\n\n // File sources give workers and workflow pieces importable paths for the\n // models registered above; the builder dedupes them.\n if (workerPool || projectionWorker || workflowsEnabled) {\n const sources = await resolveWorkerModelSources(packages, reactorLogger, {\n resolveRemote: resolveRegistryModels,\n });\n // Workers need every model; workflow pieces can do without a broken one.\n reactorBuilder.withDocumentModelSources(\n workerPool || projectionWorker\n ? sources\n : await keepImportableSources(sources, reactorLogger),\n );\n }\n workerModels = modelManifestSource(reactorBuilder);\n\n if (workerPool) {\n if (!reactorDbUrl) {\n throw new Error(\n \"unreachable: worker pool enabled without a reactor database URL\",\n );\n }\n // The builder fails the boot if a model lacks an importable source.\n reactorBuilder.withWorkerPool({\n numWorkers: workerPool.numWorkers,\n db: buildWorkerDbConfig(reactorDbUrl, workerPool),\n });\n reactorLogger.info(\n `Executor worker pool enabled: ${workerPool.numWorkers} worker threads${\n workerPool.mode === \"auto\" ? \" (auto-sized from cores)\" : \"\"\n }`,\n );\n }\n\n reactorBuilder.withReadModelFactory(\n async ({\n operationIndex,\n writeCache,\n processorManagerConsistencyTracker,\n }) => {\n const nodeProcessor = new NodeProcessor(\n baseKysely as unknown as Kysely<unknown>,\n REACTOR_SCHEMA,\n operationIndex,\n writeCache,\n processorManagerConsistencyTracker,\n );\n await nodeProcessor.init();\n return nodeProcessor;\n },\n );\n\n registerAttachmentReferenceReadModel(reactorBuilder, {\n baseKysely: baseKysely as unknown as Kysely<unknown>,\n attachmentReferenceWriter,\n });\n\n if (projectionWorker) {\n if (!reactorDbUrl) {\n throw new Error(\n \"unreachable: projection worker enabled without a reactor database URL\",\n );\n }\n const db = {\n ...buildWorkerDbConfig(reactorDbUrl, {\n dbPoolSizePerWorker: projectionWorker.dbPoolSize,\n acquireTimeoutMs: workerPool?.acquireTimeoutMs ?? 5000,\n }),\n applicationName: \"switchboard-projection\",\n };\n reactorBuilder.withReadModelCoordinatorFactory(\n createHybridProjectionCoordinatorFactory({\n shardCount: 1,\n poolSize: projectionWorker.dbPoolSize,\n db,\n onFatal: onProjectionWorkerFatal,\n }),\n );\n reactorLogger.info(\n `Projection worker enabled: 1 worker thread, pool size ${projectionWorker.dbPoolSize}`,\n );\n }\n\n reactorBuilder.withShutdownHook(async () => {\n if (apiRef.current) await apiRef.current.dispose();\n });\n\n let module: InProcessReactorClientModule;\n try {\n module = await clientBuilder.buildModule();\n } catch (error) {\n try {\n await baseKysely.destroy();\n } catch (destroyError) {\n logger.error(\n \"Aborting boot: reactor database destroy failed: @error\",\n destroyError,\n );\n }\n if (UnsupportedStoredProtocolError.isError(error)) {\n throw new StoredDocumentsRefusedError(error);\n }\n throw error;\n }\n\n if (module.reactorModule) {\n const instrumentation = new ReactorInstrumentation(module.reactorModule);\n instrumentation.start();\n reactorLogger.info(\"Reactor metrics instrumentation started\");\n }\n\n const reactorDriveSchemaDb = baseKysely.withSchema(\n REACTOR_SCHEMA,\n ) as unknown as Kysely<ReactorDriveDatabase>;\n driveNodeView = new DriveNodeView(reactorDriveSchemaDb);\n const reactorDriveClient = new ReactorDriveClient({\n reactor: module.client,\n readModel: driveNodeView,\n });\n\n ownedReactorModule = module;\n if (options.fatalErrorShutdown) {\n installFatalErrorShutdown(logger);\n }\n\n return {\n module,\n reactorDriveClient,\n attachmentReferenceProjection: { status: \"available\" as const },\n };\n };\n\n // Tear down a partially booted stack in the reactor's own order: reactor\n // first, then the api's HTTP/WS/db handles, then the database pool. An\n // owned reactor goes through its module's shutdown, so the other hooks run\n // too and a later signal joins this teardown instead of repeating it.\n const abortBoot = async (api: { dispose: () => Promise<void> }) => {\n let disposed: Promise<void> | undefined;\n const disposeApi = () => (disposed ??= api.dispose());\n apiRef.current = { dispose: disposeApi };\n const owned = ownedReactorModule;\n if (owned?.reactorModule) {\n try {\n await owned.reactorModule.shutdown();\n } catch (error) {\n logger.error(\"Aborting boot: reactor shutdown failed: @error\", error);\n }\n } else if (owned) {\n try {\n await owned.reactor.kill().completed;\n } catch (error) {\n logger.error(\"Aborting boot: reactor shutdown failed: @error\", error);\n }\n }\n // Already done by the shutdown hook unless the reactor failed to stop.\n try {\n await disposeApi();\n } catch (error) {\n logger.error(\"Aborting boot: api dispose failed: @error\", error);\n }\n };\n\n // Reading credentials from this switchboard's own reactor needs the GraphQL\n // manager, which only exists once the api is up: bind the check afterwards.\n let localCredentialCheck: CredentialCheck | undefined;\n const verifyCredential: CredentialVerifier | undefined =\n renownConfig.source === \"self\"\n ? (params) =>\n localCredentialCheck\n ? localCredentialCheck(params)\n : Promise.reject(\n new Error(\"The local renown read model is not bound yet\"),\n )\n : undefined;\n\n let defaultDriveUrl: undefined | string = undefined;\n\n // TODO get path from powerhouse config\n const basePath = process.cwd();\n\n const reportError = (error: unknown) => {\n Sentry.captureException(error);\n };\n const reporting = { logger, report: reportError };\n\n // import Vite loader only if dev mode is enabled\n let vite: ViteDevServer | undefined;\n let viteLoader: VitePackageLoader | undefined;\n if (dev) {\n const { VitePackageLoader, createViteLogger, startViteServer } =\n await import(\"@powerhousedao/reactor-api/vite\");\n vite = await startViteServer(process.cwd(), createViteLogger(logger));\n // Packages switchboard brings, like the workflow package, resolve from\n // here when the project does not install them itself.\n viteLoader = VitePackageLoader.build(vite, {\n resolveFrom: [import.meta.url],\n reportError,\n });\n }\n\n // Vetra is builder-only and bundled (not CDN-loadable); lazy-load its\n // processor only in dev, where builder tooling runs (e.g. `ph vetra`).\n const vetraProcessorFactory = dev\n ? (await import(\"@powerhousedao/vetra/processors\")).processorFactory\n : undefined;\n\n // get paths to local document models\n if (!options.disableLocalPackages) {\n packages.push(basePath);\n }\n\n // create loaders\n const packageLoaders: IPackageLoader[] = [];\n if (viteLoader) {\n packageLoaders.push(viteLoader);\n } else {\n packageLoaders.push(new ImportPackageLoader());\n }\n if (httpLoader) {\n packageLoaders.push(httpLoader);\n registryPackages?.split(\",\").forEach((p) => {\n const name = p.trim();\n if (!packages.includes(name)) {\n packages.push(name);\n }\n });\n }\n\n const apiLogger = logger.child([\"reactor-api\"]);\n // When the read-model store is on disk, hand reactor-api a factory that\n // constructs the matching PGLite (current or legacy) for the detected\n // PG_VERSION. reactor-api calls the factory synchronously, so the legacy\n // module is preloaded above.\n let pgliteFactory: PgliteFactory | undefined;\n if (readModelPgliteDir && readModelPgliteMajor !== null) {\n const openReadStore = await createPgliteStoreFactory({\n label: \"read-storage\",\n major: readModelPgliteMajor,\n parsers: \"utc-timestamps\",\n inMemory: PGLITE_IN_MEMORY,\n threaded: options.pgliteWorkers === true,\n logger,\n });\n pgliteFactory = (connectionString) =>\n openReadStore(connectionString ?? readModelPgliteDir);\n }\n\n const api = await initializeAndStartAPI(\n initializeClient,\n {\n port: serverPort,\n dbPath: readModelPath,\n pgliteFactory,\n https: options.https,\n packageLoaders: packageLoaders.length > 0 ? packageLoaders : undefined,\n packages: packages,\n processorConfig: options.processorConfig,\n processors: vetraProcessorFactory\n ? { \"@powerhousedao/vetra\": [vetraProcessorFactory] }\n : {},\n configFile: configPath,\n mcp: options.mcp ?? true,\n inspection:\n options.inspection === false ? false : { throttle: inspectionThrottle },\n logger: apiLogger,\n reportError,\n enableDocumentModelSubgraphs: options.enableDocumentModelSubgraphs,\n // Already resolved for this reactor's own identity; reuse it so an\n // invalid RENOWN_SOURCE is reported once, not once per resolution.\n renown: renownConfig,\n verifyCredential,\n },\n \"switchboard\",\n );\n apiRef.current = api;\n\n if (renownConfig.source === \"self\") {\n const { graphqlManager: manager } = api;\n // Refuse to serve rather than 401 every request: the read model comes from\n // a loaded package, so a missing one is a deployment mistake.\n if (!manager.hasSubgraphHandler(RENOWN_READ_MODEL_SUBGRAPH)) {\n await abortBoot(api);\n throw new Error(\n 'Renown credential verification is set to \"self\" (auth.renown.source ' +\n `or RENOWN_SOURCE) but no loaded package serves the ` +\n `\"${RENOWN_READ_MODEL_SUBGRAPH}\" subgraph. Install one ` +\n \"(@powerhousedao/renown-package) or set RENOWN_SOURCE=remote.\",\n );\n }\n localRenownRequest = (query, variables) =>\n manager.executeSubgraphQuery(\n RENOWN_READ_MODEL_SUBGRAPH,\n query,\n variables,\n );\n localCredentialCheck = createLocalCredentialVerifier(localRenownRequest, {\n onError: (error) =>\n logger.error(\"Renown read model query failed: @error\", error),\n });\n logger.info(\n \"Renown credentials will be verified against this switchboard's own \" +\n \"renown read model\",\n );\n }\n\n // R2.3: flag-on, the attachments plugin owns the route mount + service\n // creation at onHttpMounting; flag-off runs the inline path.\n let attachmentService:\n | ReturnType<typeof createRemoteAttachmentService>\n | undefined;\n if (pluginHost) {\n pluginHost.ctx.api = api;\n pluginHost.ctx.serverPort = serverPort;\n await pluginHost.observe(\"onHttpMounting\");\n attachmentService = pluginHost.ctx.attachmentService as\n | ReturnType<typeof createRemoteAttachmentService>\n | undefined;\n } else {\n registerAttachmentRoutes(api);\n attachmentService = createRemoteAttachmentService(\n deriveAttachmentServiceConfig(options, serverPort, renown),\n );\n }\n\n if (process.env.SENTRY_DSN) {\n // Register Sentry error handler after all routes are established.\n // The adapter calls the framework-specific Sentry setup internally.\n api.httpAdapter.setupSentryErrorHandler(Sentry);\n }\n\n const { client, graphqlManager, documentModelRegistry } = api;\n\n const lateSubgraphs: Promise<unknown>[] = [];\n if (pluginHost) {\n pluginHost.ctx.client = client;\n pluginHost.ctx.graphqlManager = graphqlManager;\n pluginHost.ctx.lateSubgraphs = lateSubgraphs;\n pluginHost.ctx.reactorClientModule = options.reactor ?? ownedReactorModule;\n await pluginHost.observe(\"onReactorReady\");\n }\n\n // The workflow runtime is a switchboard component: composed from what the\n // api handed back, registered like any other late subgraph.\n let workflows: ComposedWorkflowRuntime | undefined;\n let workflowsRetry: WorkflowSingletonRetry | undefined;\n const composeWorkflows = () =>\n composeWorkflowRuntime({\n reactorClient: client,\n clientModule: options.reactor ?? ownedReactorModule,\n relationalDb: api.relationalDb,\n // A Postgres read model outlives the pod; a key file beside it would not.\n secretsKeyFile: readModelPgliteDir === null ? false : undefined,\n // The stable half of the default singleton owner name. Absolute, so\n // two Switchboards in different working directories differ.\n storageId:\n readModelPgliteDir === null\n ? readModelPath\n : path.resolve(readModelPath),\n attachments: createAttachmentClient(api.attachments.service),\n attachmentAccess: api.attachmentAccess,\n // The workflow package's own HTTP namespace: its webhook endpoints live\n // under it, not under the reactor's.\n webhooks: api.httpRoutes.scopeFor(WORKFLOW_PACKAGE_NAME).webhooks,\n http: api.httpRoutes.scopeFor(WORKFLOW_PACKAGE_NAME),\n authorizationService: api.authorizationService,\n // The manager that already loads this reactor's packages: the project it\n // runs in is one of them, so its own pieces arrive with the rest.\n pieces: api.packageManager,\n pieceRegistryUrl: registryUrl,\n models: workerModels,\n // The piece pool leaves the reactor's threads their share of the cores.\n reactorThreads:\n (workerPool?.numWorkers ?? 0) + (projectionWorker ? 1 : 0),\n logger: logger.child([\"workflow-runtime\"]),\n exclusiveJournal: readModelPgliteDir !== null,\n onSingletonLost: workflowSingletonLossHandler(logger),\n // The providers observability.mts registered before this module loaded.\n telemetry: {\n tracer: trace.getTracer(WORKFLOW_TELEMETRY_SCOPE),\n meter: metrics.getMeter(WORKFLOW_TELEMETRY_SCOPE),\n },\n });\n const registerWorkflowSubgraph = (composed: ComposedWorkflowRuntime) => {\n const WorkflowRuntimeSubgraph = composed.subgraph;\n const workflowSubgraph = new WorkflowRuntimeSubgraph({\n reactorClient: client,\n http: graphqlManager.scopeForPackage(WORKFLOW_PACKAGE_NAME),\n relationalDb: api.relationalDb,\n analyticsStore: undefined as never,\n graphqlManager,\n syncManager: api.syncManager,\n authorizationService: graphqlManager.getAuthorizationService(),\n path: graphqlManager.getBasePath(),\n attachments: api.attachmentClientProvider,\n });\n return graphqlManager\n .registerSubgraphInstance(workflowSubgraph, \"graphql\", false)\n .catch((error: unknown) => {\n reportFailure(\n reporting,\n error,\n \"Failed to register workflow-runtime subgraph: @error\",\n );\n });\n };\n if (!pluginHost && workflowsEnabled) {\n try {\n workflows = await composeWorkflows();\n } catch (error) {\n // Without the claim this host must not run workflows, but everything\n // else it serves still works, so it boots without the runtime.\n if (!isWorkflowSingletonConflict(error)) throw error;\n logger.warn(\n `Workflows are enabled but another live process (\"${error.owner ?? \"unknown\"}\") ` +\n `holds the workflow singleton until ${error.expiresAt ?? \"unknown\"}. ` +\n \"This Switchboard has booted WITHOUT the workflow runtime: no \" +\n \"trigger of any kind fires here, and the workflow GraphQL face is \" +\n \"absent. Everything else serves normally. Stop the other owner, or \" +\n \"set PH_WORKFLOWS_SINGLETON_OWNER to the same stable name on the \" +\n \"slot that owns workflows. This Switchboard retries the claim and \" +\n \"starts workflows once the lease comes free.\",\n );\n workflowsRetry = retryWorkflowSingleton({\n compose: composeWorkflows,\n onComposed: async (composed) => {\n try {\n await composed.start();\n } catch (error) {\n // Hands the lease back so a retry or another replica can claim it.\n try {\n await composed.stop();\n } catch (stopError) {\n logger.error(\n \"Stopping the late workflow runtime failed: @error\",\n stopError,\n );\n }\n throw error;\n }\n logger.info(\"Workflow runtime started\");\n workflows = composed;\n await registerWorkflowSubgraph(composed);\n // Past boot nothing else rebuilds the router, so a subgraph\n // registered now is not served until this runs.\n try {\n await graphqlManager.updateRouter(true);\n } catch (error) {\n reportFailure(\n reporting,\n error,\n \"Mounting the late workflow-runtime subgraph failed: @error\",\n );\n }\n },\n logger,\n });\n }\n }\n if (workflows) {\n lateSubgraphs.push(registerWorkflowSubgraph(workflows));\n await workflows.start();\n logger.info(\"Workflow runtime started\");\n api.inspection?.facts.setWorkflows(true);\n }\n\n // Plugins register their subgraphs here (push into lateSubgraphs, or mount\n // directly like privacy). The call site carries the inline privacy block's\n // failure semantics: stop workflows, abort the partial boot, rethrow.\n if (pluginHost) {\n pluginHost.ctx.workflowsOrchestration = {\n enabled: options.workflows?.enabled === true,\n composeWorkflows,\n registerWorkflowSubgraph,\n updateRouter: () => graphqlManager.updateRouter(true),\n reportMountFailure: (error: unknown) =>\n reportFailure(\n reporting,\n error,\n \"Mounting the late workflow-runtime subgraph failed: @error\",\n ),\n setWorkflowsFact: () => api.inspection?.facts.setWorkflows(true),\n };\n try {\n await pluginHost.observe(\"onSubgraphsRegistering\");\n } catch (error) {\n await (\n pluginHost.ctx.workflowsRetry as WorkflowSingletonRetry | undefined\n )?.stop();\n await (\n pluginHost.ctx.workflows as ComposedWorkflowRuntime | undefined\n )?.stop();\n await abortBoot(api);\n throw error;\n }\n }\n\n let privacy: RunningPrivacy | undefined;\n if (!pluginHost && privacyConfig.enabled) {\n // The caller's reactor signs with a signer only the caller knows.\n const signer = options.reactor\n ? options.privacy?.signer\n : (options.privacy?.signer ?? renown?.signer);\n try {\n privacy = await startPrivacy({\n config: privacyConfig,\n reactorModule: (options.reactor ?? ownedReactorModule)?.reactorModule,\n signer,\n authorizationService: api.authorizationService,\n documentPermissionService: api.documentPermissionService,\n graphqlManager,\n reactorClient: client,\n logger: logger.child([\"privacy\"]),\n });\n } catch (error) {\n await workflowsRetry?.stop();\n await workflows?.stop();\n await abortBoot(api);\n throw error;\n }\n }\n\n // Ahead of the api: the runtime's store lives in the read-model database\n // that dispose closes, and its children outlive the reactor otherwise.\n // Memoized: the reactor's shutdown hook and a caller can both reach it.\n const stopCatchUpLoad = ownedReactorModule\n ? feedCatchUpPriority(catchUpPriority, api.httpServer)\n : () => {};\n let apiDrained: Promise<void> | undefined;\n const drainApi = () =>\n (apiDrained ??= (async () => {\n stopCatchUpLoad();\n if (pluginHost) await pluginHost.observe(\"onShutdown\");\n await privacy?.stop();\n await workflowsRetry?.stop();\n await workflows?.stop();\n await api.dispose();\n })());\n apiRef.current = { dispose: drainApi };\n // An owned reactor's shutdown drains the api through the hook above, in the\n // signal path's order: kill, hooks, database. A caller's reactor is the\n // caller's to stop, so only the api is drained.\n const ownedReactor = ownedReactorModule?.reactorModule;\n const shutdown = ownedReactor ? () => ownedReactor.shutdown() : drainApi;\n\n // Wire up dynamic package management if HTTP loader is configured\n if (httpLoader) {\n const packageManagementService = new PackageManagementService({\n defaultRegistryUrl: registryUrl,\n httpLoader,\n documentModelRegistry,\n packageManager: api.packageManager,\n });\n\n packageManagementService.setOnModelsChanged(() => {\n graphqlManager\n .regenerateDocumentModelSubgraphs()\n .catch((error: unknown) => {\n reportFailure(\n reporting,\n error,\n \"Failed to regenerate document model subgraphs: @error\",\n );\n });\n });\n\n const packagesSubgraph = new PackagesSubgraph({\n relationalDb: undefined as never,\n analyticsStore: undefined as never,\n reactorClient: client,\n graphqlManager,\n syncManager: api.syncManager,\n path: graphqlManager.getBasePath(),\n authorizationService: graphqlManager.getAuthorizationService(),\n packageManagementService,\n http: graphqlManager.scopeForPackage(\"@powerhousedao/switchboard\"),\n attachments: api.attachmentClientProvider,\n });\n\n lateSubgraphs.push(\n graphqlManager\n .registerSubgraphInstance(packagesSubgraph, \"graphql\", false)\n .catch((error: unknown) => {\n reportFailure(\n reporting,\n error,\n \"Failed to register packages subgraph: @error\",\n );\n }),\n );\n }\n\n if (driveNodeView) {\n graphqlManager.setAdditionalContextFields({\n readModel: driveNodeView,\n });\n\n const authorizationService = graphqlManager.getAuthorizationService();\n const reactorDriveSubgraph = {\n name: REACTOR_DRIVE_SUBGRAPH_NAME,\n path: graphqlManager.getBasePath(),\n resolvers: createReactorDriveResolvers({\n reactorClient: client,\n readModel: driveNodeView,\n hostCanRead: (documentId, address) =>\n authorizationService.canRead(\n documentId as CanonicalDocumentId,\n address,\n ),\n }),\n typeDefs: reactorDriveSubgraphTypeDefs,\n reactorClient: client,\n relationalDb: undefined as never,\n };\n\n lateSubgraphs.push(\n graphqlManager\n .registerSubgraphInstance(reactorDriveSubgraph, \"graphql\", false)\n .catch((error: unknown) => {\n reportFailure(\n reporting,\n error,\n \"Failed to register reactor-drive subgraph: @error\",\n );\n }),\n );\n }\n\n void runDetached(\n \"Marking the API ready\",\n async () => {\n await Promise.allSettled(lateSubgraphs);\n try {\n await graphqlManager.updateRouter(true);\n } catch (error) {\n reportFailure(\n reporting,\n error,\n \"Final router update before readiness failed: @error\",\n );\n }\n api.readiness.markReady();\n },\n reporting,\n );\n\n // Create default drive if provided\n if (options.drive) {\n if (!renown) {\n throw new Error(\"Cannot create default drive without Renown identity\");\n }\n\n const driveType = options.drive.documentType ?? \"powerhouse/document-drive\";\n if (driveType === \"powerhouse/reactor-drive\") {\n defaultDriveUrl = await addDefaultReactorDrive(\n client,\n options.drive,\n serverPort,\n logger,\n );\n } else {\n defaultDriveUrl = await addDefaultDrive(\n client,\n options.drive,\n serverPort,\n logger,\n );\n }\n }\n\n // add vite middleware after express app is initialized if applicable\n if (vite) {\n api.httpAdapter.mountRawMiddleware(vite.middlewares);\n }\n\n // Connect to remote drives AFTER packages are loaded\n if (remoteDrives.length > 0) {\n for (const remoteDriveUrl of remoteDrives) {\n let driveId: string | undefined;\n\n try {\n const { syncManager } = api;\n const parsed = parseDriveUrl(remoteDriveUrl);\n driveId = parsed.driveId;\n const remoteName = `remote-drive-${driveId}-${crypto.randomUUID()}`;\n await syncManager.add(remoteName, DriveCollectionId.forDrive(driveId), {\n type: \"gql\",\n parameters: { url: parsed.graphqlEndpoint },\n });\n logger.debug(\"Remote drive @remoteDriveUrl synced\", remoteDriveUrl);\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes(\"already exists\")\n ) {\n logger.debug(\n \"Remote drive already added: @remoteDriveUrl\",\n remoteDriveUrl,\n );\n driveId = remoteDriveUrl.split(\"/\").pop();\n } else {\n logger.error(\n \"Failed to connect to remote drive @remoteDriveUrl: @error\",\n remoteDriveUrl,\n error,\n );\n }\n } finally {\n // Construct local URL once in finally block\n if (!defaultDriveUrl && driveId) {\n const protocol = options.https ? \"https\" : \"http\";\n defaultDriveUrl = `${protocol}://localhost:${serverPort}/d/${driveId}`;\n }\n }\n }\n }\n\n // Drives exist (default created, remotes attached) — the barrier after the\n // future core drive seeding (R2 step 2 replaces the two blocks above).\n if (pluginHost) await pluginHost.observe(\"onDrivesReady\");\n\n return {\n defaultDriveUrl,\n api,\n reactor: client,\n attachmentService,\n attachmentReferenceProjection: api.attachmentReferenceProjection,\n // Read live: losing the singleton turns it unavailable.\n get workflowTriggers() {\n return (\n workflows ??\n (pluginHost?.ctx.workflows as ComposedWorkflowRuntime | undefined)\n )?.triggers;\n },\n workflowsEnabled,\n modelManifest: () => workerModels?.modelManifest() ?? [],\n privacy: (() => {\n const running =\n privacy ?? (pluginHost?.ctx.privacy as RunningPrivacy | undefined);\n return running ? { erasure: running.erasure } : undefined;\n })(),\n mcpEnabled: options.mcp !== false,\n inspectionEnabled: options.inspection !== false,\n inspector: api.inspection?.inspector,\n renown,\n port: serverPort,\n shutdown,\n };\n}\n\n/**\n * Boot the switchboard HTTP/GraphQL/MCP stack on top of a reactor.\n *\n * If `options.reactor` is provided, the switchboard reuses it instead of\n * building its own — the caller then owns the reactor's lifecycle and is\n * responsible for invoking `SwitchboardReactor.shutdown()` from their own\n * teardown / SIGINT path. The switchboard will not reach into the caller's\n * reactor; killing the reactor alone leaves the api/GraphQL/MCP resources\n * dangling until the process exits.\n *\n * When `options.reactor` is omitted, the switchboard builds and owns the\n * reactor. `shutdown()` on the returned handle then runs the reactor\n * module's `shutdown()`: `kill()`, the `withShutdownHook` chain that drains\n * the api (HTTP server, GraphQL, MCP, attachments, read-model db), then the\n * reactor database. It does not exit the process. It is the same memoized\n * teardown the SIGINT/SIGTERM handlers (`withSignalHandlers`) run, so calling\n * it twice, or receiving a signal around it, tears down once.\n */\nexport const startSwitchboard = async (\n options: StartServerOptions = {},\n): Promise<SwitchboardReactor> => {\n const requestedPort = options.port ?? DEFAULT_PORT;\n const logger = options.logger ?? defaultLogger;\n // Here as well as in index.mts, so a host embedding the server is profiled.\n if (process.env.PYROSCOPE_SERVER_ADDRESS) {\n await initProfilerFromEnv(process.env).catch((error: unknown) =>\n logger.error(\"Error starting profiler: @error\", error),\n );\n }\n const serverPort = await resolveServerPort(\n requestedPort,\n options.strictPort ?? false,\n logger,\n );\n\n // Initialize feature flags\n const featureFlags = await initFeatureFlags();\n\n const enableDocumentModelSubgraphs = await featureFlags.getBooleanValue(\n DOCUMENT_MODEL_SUBGRAPHS_ENABLED,\n options.enableDocumentModelSubgraphs ??\n DOCUMENT_MODEL_SUBGRAPHS_ENABLED_DEFAULT,\n );\n\n options.enableDocumentModelSubgraphs = enableDocumentModelSubgraphs;\n\n // CLASSIC resolution of the carved subsystems' switches — flag-on, the\n // plugins own these (presence is activation): the resolvers are skipped so\n // an ABSENT plugin can actually deactivate its subsystem (initServer\n // normalizes unset values to off after transformServerOptions). An explicit\n // caller option always wins on both paths. The inspection flag is a core\n // capability (not carved) and resolves classically either way.\n if (!isPluginHostEnabled()) {\n options.mcp = await resolveMcpEnabled({\n featureFlags,\n option: options.mcp,\n });\n const configPathForFlags = resolveConfigPath(options.configFile);\n const workflowsEnabled = await resolveWorkflowsEnabled({\n featureFlags,\n override: options.workflows?.enabled,\n configEnabled: readConfigWorkflowsEnabled(configPathForFlags),\n });\n options.workflows = { enabled: workflowsEnabled };\n }\n options.inspection = await resolveInspectionEnabled({\n featureFlags,\n option: options.inspection,\n });\n options.pgliteWorkers = await resolvePgliteWorkersEnabled({\n featureFlags,\n option: options.pgliteWorkers,\n });\n // This switchboard's own identity authenticates against the same Renown\n // instance it verifies incoming credentials against, unless told otherwise.\n const renownConfig = resolveRenownConfig(\n getConfig(resolveConfigPath(options.configFile)).auth?.renown,\n process.env,\n logger,\n );\n options.identity = {\n ...options.identity,\n baseUrl: options.identity?.baseUrl ?? renownConfig.url,\n // Under a shell's PH_USER_DATA_DIR the identity lives in the user's .ph\n // tree with the stores, never in the install dir. Unset: unchanged —\n // renown's own `<cwd>/.ph/.keypair.json` default applies.\n keypairPath:\n options.identity?.keypairPath ??\n (process.env.PH_USER_DATA_DIR\n ? path.join(resolvePhDir(), \".keypair.json\")\n : undefined),\n };\n\n logger.info(\n \"Feature flags: @flags\",\n JSON.stringify(\n {\n DOCUMENT_MODEL_SUBGRAPHS_ENABLED: enableDocumentModelSubgraphs,\n MCP_ENABLED: options.mcp,\n INSPECTION_ENABLED: options.inspection,\n PH_PGLITE_WORKERS: options.pgliteWorkers,\n PH_WORKFLOWS_ENABLED: options.workflows?.enabled,\n },\n null,\n 2,\n ),\n );\n\n // Initialize Renown if identity options are provided or keypair exists\n let renown: IRenown | null = null;\n try {\n renown = await initRenown(options.identity);\n } catch (e) {\n logger.warn(\"Failed to initialize ConnectCrypto: @error\", e);\n if (options.identity.requireExisting) {\n throw new Error(\n 'Identity required but failed to initialize. Run \"ph login\" first.',\n { cause: e },\n );\n }\n }\n\n try {\n return await initServer(serverPort, options, renown, renownConfig);\n } catch (e) {\n Sentry.captureException(e);\n if (StoredDocumentsRefusedError.isError(e)) {\n logger.error(e.message);\n } else {\n logger.error(\"App crashed: @error\", e);\n }\n throw e;\n }\n};\n\nexport {\n applySwitchboardReactorDefaults,\n type SwitchboardReactorDefaultsOptions,\n} from \"./builder-defaults.mjs\";\nexport * from \"./types.js\";\nexport {\n StoredDocumentsRefusedError,\n resolveUnsupportedStoredDocuments,\n} from \"./unsupported-stored-documents.mjs\";\n\nif (import.meta.main) {\n await startSwitchboard({ fatalErrorShutdown: true });\n}\n\n/** `PH_CATCH_UP_PRIORITY`: `dynamic` (the default) or a fixed level `0`-`7`. */\nfunction catchUpPrioritySettingFromEnv(\n value: string | undefined,\n logger: ILogger,\n): CatchUpPrioritySetting {\n const setting = parseCatchUpPriority(value);\n if (setting) return setting;\n logger.warn(\n \"PH_CATCH_UP_PRIORITY=@Value is neither dynamic nor a level 0-7; using dynamic\",\n JSON.stringify(value),\n );\n return { mode: \"dynamic\" };\n}\n\n/**\n * Feeds the priority this server's request load and main-thread event-loop\n * delay, and ticks its controller every second. Returns the stop.\n */\nfunction feedCatchUpPriority(\n priority: CatchUpPriority,\n server: http.Server,\n): () => void {\n const recorder = new RequestLoadRecorder({\n eventLoopDelay: new NodeEventLoopDelay(),\n });\n recorder.attach(server);\n priority.setLoadSource(recorder);\n const stopTicking = priority.startTicking();\n return () => {\n stopTicking();\n priority.setLoadSource(undefined);\n recorder.stop();\n };\n}\n"],"names":["fs","logger","logger","fs","fs","path"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,MAAa,sBAAsB,CAAC,IAAI,EAAE;AAK1C,eAAsB,kBACpB,SACwB;CACxB,IAAI;EACF,MAAM,MAAM,MAAMA,SAAG,SAAS,KAAK,KAAK,SAAS,YAAY,GAAG,MAAM;EACtE,MAAM,QAAQ,SAAS,IAAI,KAAK,GAAG,EAAE;EACrC,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;CAC1C,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAgB,iBAAiB,OAA0C;CACzE,OAAQ,oBAA0C,SAAS,KAAK;AAClE;;;;;;;AAQA,SAAgB,oBACd,KACyB;CACzB,IAAI,QAAQ,KAAA,KAAa,IAAI,KAAK,MAAM,IAAI,OAAO;CACnD,MAAM,SAAS,OAAO,GAAG;CACzB,IAAI,OAAO,UAAU,MAAM,KAAK,iBAAiB,MAAM,GAAG,OAAO;CACjE,MAAM,IAAI,MACR,uCAAuC,oBAAoB,KAAK,IAAI,EAAE,SAAS,IAAI,EACr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G;EACV,OAAO,iBAAiB,CAAC;EACzB,IAAI,4BAA4B,QAAQ,CAAC,GACvC,OAAO,MAAM,EAAE,OAAO;OAEtB,OAAO,MAAM,uBAAuB,CAAC;EAEvC,MAAM;CACR;AACF;AAYA,IAAI,YAAY,MACd,MAAM,iBAAiB,EAAE,oBAAoB,KAAK,CAAC;;AAIrD,SAAS,8BACP,OACA,QACwB;CACxB,MAAM,UAAU,qBAAqB,KAAK;CAC1C,IAAI,SAAS,OAAO;CACpB,OAAO,KACL,iFACA,KAAK,UAAU,KAAK,CACtB;CACA,OAAO,EAAE,MAAM,UAAU;AAC3B;;;;;AAMA,SAAS,oBACP,UACA,QACY;CACZ,MAAM,WAAW,IAAI,oBAAoB,EACvC,gBAAgB,IAAI,mBAAmB,EACzC,CAAC;CACD,SAAS,OAAO,MAAM;CACtB,SAAS,cAAc,QAAQ;CAC/B,MAAM,cAAc,SAAS,aAAa;CAC1C,aAAa;EACX,YAAY;EACZ,SAAS,cAAc,KAAA,CAAS;EAChC,SAAS,KAAK;CAChB;AACF","debug_id":"23ac9e84-b25f-5218-b443-313ef3078eee"}
package/dist/server.d.mts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { n as WorkflowTriggersCapability } from "./workflow-runtime-7GaJ13c9.mjs";
2
2
  import { ILogger } from "document-model";
3
- import "@powerhousedao/reactor-api/pglite-node";
4
- import { ChannelScheme, Database, IDocumentModelLoader, IReactorClient, InProcessReactorClientModule, JwtHandler, ModelManifestEntry, PoolInstrumentation, ReactorBuilder, ReactorClientBuilder, ReactorFeatureFlags, ReactorStorageFacts, SignerConfig, UnsupportedStoredDocuments, UnsupportedStoredProtocolError } from "@powerhousedao/reactor";
3
+ import { ChannelScheme, Database, IDocumentModelLoader, IInspector, IReactorClient, InProcessReactorClientModule, JwtHandler, ModelManifestEntry, PoolInstrumentation, ReactorBuilder, ReactorClientBuilder, ReactorFeatureFlags, ReactorStorageFacts, SignerConfig, UnsupportedStoredDocuments, UnsupportedStoredProtocolError } from "@powerhousedao/reactor";
5
4
  import { AttachmentReferenceProjectionCapability } from "@powerhousedao/reactor-api";
5
+ import "@powerhousedao/reactor-api/pglite-node";
6
6
  import { IAttachmentService } from "@powerhousedao/reactor-attachments";
7
7
  import { IRenown } from "@renown/sdk/node";
8
8
  import { Kysely } from "kysely";
@@ -135,6 +135,10 @@ export type StartServerOptions = {
135
135
  /** Mount the read-only inspection subgraph at `/graphql/inspection`. On by
136
136
  * default; `false` wins over INSPECTION_ENABLED, which can turn it off. */
137
137
  inspection?: boolean;
138
+ /** Open each PGlite store (reactor-storage, read-storage) in its own worker
139
+ * thread. Wins either way over PH_PGLITE_WORKERS; unset, the env var
140
+ * decides, then PGLITE_WORKERS_DEFAULT. */
141
+ pgliteWorkers?: boolean;
138
142
  /** Powerhouse workflows: the runtime, its subgraph, its webhooks and its
139
143
  * document models. Wins over PH_WORKFLOWS_ENABLED and the config file. */
140
144
  workflows?: {
@@ -231,6 +235,8 @@ export type SwitchboardReactor = {
231
235
  mcpEnabled: boolean;
232
236
  /** Whether `/graphql/inspection` is mounted, after the option and INSPECTION_ENABLED. */
233
237
  inspectionEnabled: boolean;
238
+ /** The reactor's inspector, as the host reads it (processors, catch-up); undefined without inspection. */
239
+ inspector: IInspector | undefined;
234
240
  /** The Renown instance if identity was initialized */
235
241
  renown: IRenown$1 | null;
236
242
  /**
@@ -331,6 +337,8 @@ export declare function createReactorKysely(opts: {
331
337
  * path never reads.
332
338
  */
333
339
  hostPoolSize: () => number;
340
+ /** Open the PGlite store in its own worker thread. */
341
+ pgliteWorkers: boolean;
334
342
  logger: ILogger;
335
343
  }): Promise<ReactorStorage>;
336
344
  export interface PgliteStorageDirs {
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.mts","names":[],"sources":["../src/pglite-version.ts","../src/privacy.mts","../src/types.ts","../src/builder-defaults.mts","../src/unsupported-stored-documents.mts","../src/server.mts"],"mappings":";;;;;;;;;;;;;;;cASa;KACD,2BAA2B;;;KCe3B;;EAEV;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;;;;;;;EAOA;EACA,QAAQ;IACN,QAAQ;iBA2DK;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;wBAcc,yBAAyB;EACvC;EACA;;EAEA;EACA;IACE;;wBAgCY,8BACd,SAAS,KAAK,uDACd,oBACA,QAAQ;EACL;EAAmB,YAAY;;;;;;;;;;;;;;;;;;;;qBAqoCvB,mBAAgB,UAClB,uBACR,QAAQ"}
1
+ {"version":3,"file":"server.d.mts","names":[],"sources":["../src/pglite-version.ts","../src/privacy.mts","../src/types.ts","../src/builder-defaults.mts","../src/unsupported-stored-documents.mts","../src/server.mts"],"mappings":";;;;;;;;;;;;;;;cAYa;KACD,2BAA2B;;;KCY3B;;EAEV;;EAEA;;EAEA,SAAS;;;;;;;;;;YCPC;;YAKA,wBAAwB;EAClC,eAAe;;YAGL;EACV;EACA;EACA;;YAGU;;EAEV;;;;;EAKA;;EAGA;;YAGU;;;;;;;;;;;;;;;;;;;;;EAqBV,UAAU;;;;;;;;EAQV;;;;;;;EAOA;;;;;;;EAOA;EACA;EACA;;;;;;EAMA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA;IAEM;IACA;;;;;;;EASN,WAAW;;EAEX;;;EAGA;;;;;;EAMA,oBAAoB;;;EAGpB;;;;EAIA;;;EAGA;IACE;;;EAGF,UAAU;EACV,kBAAkB;EAClB;EACA;;;;;;EAMA;EACA,SAAS;;;;;;;;;;EAUT;;;;;;;;;;EAUA;;;;;;;;;EASA;IACE;IACA;IACA;;;;;;;;;;;EAWF;IACE;IACA;;;;;;;;;EASF,6BAA6B;;YAGnB;EACV;EACA,SAAS;;;;EAIT,mBAAmB;;EAEnB,+BAA+B;;;EAG/B,mBAAmB;;EAEnB;;EAEA,iBAAiB;;EAEjB;IAAY,SAAS;;;EAErB;;EAEA;;EAEA,WAAW;;EAEX,QAAQ;;;;;EAKR;;;;;;;;EAQA,gBAAgB;;;;KCtON;EAIV,iBAAiB;;EAEjB,mBAAmB;;EAEnB;;;;;;;EAOA,gBAAgB;;EAEhB;;EAEA;IACE;IACA,eAAe,QAAQ;;;EAGzB,sBAAsB;EACtB,SAAS;;;;;;EAMT,SAAS;;;;;EAKT,cAAc,KAAK;;EAEnB,wBAAwB;;wBAiBV,gCACd,gBAAgB,gBAChB,eAAe,sBACf,UAAS;;;;wBCvEK,kCACd,OAAO,wCACP,KAAK,OAAO,aACX;;qBAaU,oCAAoC;WACtC;IAAqB;IAAkB;;WACvC;EAET,YAAY,OAAO;SAcZ,QAAQ,iBAAiB,SAAS;;;;;;;;;wBC+JrB,gBAAgB,eAAe;;;;;;KAqFhD;EACH,QAAQ,OAAO;EACf,qBAAqB;EACrB,cAAc;;wBAGM,oBAAoB;EACxC;EACA;EACA,oBAAoB;EACpB;;;;;;;EAOA;;EAEA;EACA,QAAQ;IACN,QAAQ;iBAyDK;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;wBAcc,yBAAyB;EACvC;EACA;;EAEA;EACA;IACE;;wBAgCY,8BACd,SAAS,KAAK,uDACd,oBACA,QAAQ;EACL;EAAmB,YAAY;;;;;;;;;;;;;;;;;;;;qBA8oCvB,mBAAgB,UAClB,uBACR,QAAQ"}
package/dist/server.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as startSwitchboard, i as resolvePgliteStorageDirs, n as deriveAttachmentServiceConfig, o as StoredDocumentsRefusedError, r as isPortAvailable, s as resolveUnsupportedStoredDocuments, t as createReactorKysely, u as applySwitchboardReactorDefaults } from "./server-nRWFjnu3.mjs";
2
+ import { a as startSwitchboard, i as resolvePgliteStorageDirs, n as deriveAttachmentServiceConfig, o as StoredDocumentsRefusedError, r as isPortAvailable, s as resolveUnsupportedStoredDocuments, t as createReactorKysely, u as applySwitchboardReactorDefaults } from "./server-CJjK7WpR.mjs";
3
3
  export { StoredDocumentsRefusedError, applySwitchboardReactorDefaults, createReactorKysely, deriveAttachmentServiceConfig, isPortAvailable, resolvePgliteStorageDirs, resolveUnsupportedStoredDocuments, startSwitchboard };
4
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="aff1b0f5-d496-512e-8bc0-42dc7af0ea1f")}catch(e){}}();
5
- //# debugId=aff1b0f5-d496-512e-8bc0-42dc7af0ea1f
4
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="52766dfd-548d-5de3-917b-e43bc4914e89")}catch(e){}}();
5
+ //# debugId=52766dfd-548d-5de3-917b-e43bc4914e89