@powerhousedao/clint 6.3.0-dev.9 → 6.4.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/dist/build-DZIv63eB.mjs +77 -0
  2. package/dist/build-DZIv63eB.mjs.map +1 -0
  3. package/dist/{build-skills-BnqGyuCH.mjs → build-skills-BNEOn-cl.mjs} +15 -6
  4. package/dist/build-skills-BNEOn-cl.mjs.map +1 -0
  5. package/dist/dist--xzirmg-.mjs +655 -0
  6. package/dist/dist--xzirmg-.mjs.map +1 -0
  7. package/dist/glob-CGjvhxgW.mjs +48 -0
  8. package/dist/glob-CGjvhxgW.mjs.map +1 -0
  9. package/dist/index-C3-HSfKb.d.mts +389 -0
  10. package/dist/index-C3-HSfKb.d.mts.map +1 -0
  11. package/dist/index.d.mts +55 -303
  12. package/dist/index.d.mts.map +1 -1
  13. package/dist/index.mjs +7 -8
  14. package/dist/integrations/mastra/index.d.mts +248 -0
  15. package/dist/integrations/mastra/index.d.mts.map +1 -0
  16. package/dist/integrations/mastra/index.mjs +509 -0
  17. package/dist/integrations/mastra/index.mjs.map +1 -0
  18. package/dist/integrations/powerhouse/index.d.mts +4 -0
  19. package/dist/integrations/powerhouse/index.mjs +3 -0
  20. package/dist/markdown-BUeGwhbR.mjs +1588 -0
  21. package/dist/markdown-BUeGwhbR.mjs.map +1 -0
  22. package/dist/powerhouse-BDnj7kqd.mjs +1922 -0
  23. package/dist/powerhouse-BDnj7kqd.mjs.map +1 -0
  24. package/dist/{proxy-BFR8GScT.mjs → proxy-ji3EHzLn.mjs} +128 -28
  25. package/dist/proxy-ji3EHzLn.mjs.map +1 -0
  26. package/dist/remote-reactor-BQzq4yfO.mjs +69 -0
  27. package/dist/remote-reactor-BQzq4yfO.mjs.map +1 -0
  28. package/dist/{start-b7Mn2cxB.mjs → repl-Czb7u0x_.mjs} +6 -29
  29. package/dist/repl-Czb7u0x_.mjs.map +1 -0
  30. package/dist/runners/cli-runner.d.mts +339 -0
  31. package/dist/runners/cli-runner.d.mts.map +1 -0
  32. package/dist/runners/cli-runner.mjs +324 -0
  33. package/dist/runners/cli-runner.mjs.map +1 -0
  34. package/dist/runners/mastra-runner.d.mts +5 -3
  35. package/dist/runners/mastra-runner.d.mts.map +1 -1
  36. package/dist/runners/mastra-runner.mjs +10 -60
  37. package/dist/runners/mastra-runner.mjs.map +1 -1
  38. package/dist/runners/proxy-runner.d.mts +281 -0
  39. package/dist/runners/proxy-runner.d.mts.map +1 -0
  40. package/dist/runners/proxy-runner.mjs +91 -0
  41. package/dist/runners/proxy-runner.mjs.map +1 -0
  42. package/dist/schema-BEKAZGyT.mjs +47 -0
  43. package/dist/schema-BEKAZGyT.mjs.map +1 -0
  44. package/dist/{src-BebNN3xc.mjs → src-BehwgLP6.mjs} +395 -1481
  45. package/dist/src-BehwgLP6.mjs.map +1 -0
  46. package/dist/start-BHn9LIyX.mjs +37 -0
  47. package/dist/start-BHn9LIyX.mjs.map +1 -0
  48. package/dist/store-CxqB-OrX.mjs +101 -0
  49. package/dist/store-CxqB-OrX.mjs.map +1 -0
  50. package/dist/{stream-DVuufwIj.mjs → stream-BguHx7vC.mjs} +4 -2
  51. package/dist/{stream-DVuufwIj.mjs.map → stream-BguHx7vC.mjs.map} +1 -1
  52. package/dist/testing/index.d.mts +81 -0
  53. package/dist/testing/index.d.mts.map +1 -0
  54. package/dist/testing/index.mjs +131 -0
  55. package/dist/testing/index.mjs.map +1 -0
  56. package/dist/{types-CRkoD-Mm.d.mts → types-CF6GuPJd.d.mts} +241 -261
  57. package/dist/types-CF6GuPJd.d.mts.map +1 -0
  58. package/dist/types-CbHJ-ZnH.d.mts +60 -0
  59. package/dist/types-CbHJ-ZnH.d.mts.map +1 -0
  60. package/package.json +44 -25
  61. package/dist/build-skills-BnqGyuCH.mjs.map +0 -1
  62. package/dist/dist-CUltriBW.mjs +0 -1628
  63. package/dist/dist-CUltriBW.mjs.map +0 -1
  64. package/dist/drive-Bu9zoFrO.mjs +0 -85
  65. package/dist/drive-Bu9zoFrO.mjs.map +0 -1
  66. package/dist/esm-C1DOsF1a.mjs +0 -13140
  67. package/dist/esm-C1DOsF1a.mjs.map +0 -1
  68. package/dist/events-BnwGFTjv.mjs +0 -237
  69. package/dist/events-BnwGFTjv.mjs.map +0 -1
  70. package/dist/folders-BYO1Wqqb.mjs +0 -256
  71. package/dist/folders-BYO1Wqqb.mjs.map +0 -1
  72. package/dist/local-signer-EFzJV3bn.mjs +0 -128
  73. package/dist/local-signer-EFzJV3bn.mjs.map +0 -1
  74. package/dist/markdown-D-sP2zw_.mjs +0 -275
  75. package/dist/markdown-D-sP2zw_.mjs.map +0 -1
  76. package/dist/proxy-BFR8GScT.mjs.map +0 -1
  77. package/dist/proxy-routes-DP3ztsnS.mjs +0 -215
  78. package/dist/proxy-routes-DP3ztsnS.mjs.map +0 -1
  79. package/dist/reactor-C9VIUX1H.mjs +0 -51
  80. package/dist/reactor-C9VIUX1H.mjs.map +0 -1
  81. package/dist/runners/clint-runner.d.mts +0 -398
  82. package/dist/runners/clint-runner.d.mts.map +0 -1
  83. package/dist/runners/clint-runner.mjs +0 -519
  84. package/dist/runners/clint-runner.mjs.map +0 -1
  85. package/dist/services-9E-r0nWl.mjs +0 -999
  86. package/dist/services-9E-r0nWl.mjs.map +0 -1
  87. package/dist/src-BebNN3xc.mjs.map +0 -1
  88. package/dist/start-b7Mn2cxB.mjs.map +0 -1
  89. package/dist/subscriptions-CfiflAsI.mjs +0 -38
  90. package/dist/subscriptions-CfiflAsI.mjs.map +0 -1
  91. package/dist/switchboard-CyvOavqL.mjs +0 -57
  92. package/dist/switchboard-CyvOavqL.mjs.map +0 -1
  93. package/dist/types-CRkoD-Mm.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"mastra-runner.mjs","names":[],"sources":["../../src/integrations/powerhouse/remote-reactor.ts","../../src/integrations/powerhouse/reactor-tools.ts","../../src/runners/agent-provider.ts","../../src/runners/mastra-runner.ts"],"sourcesContent":["import type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport type { ReactorProtocol } from \"@powerhousedao/host-core\";\n\n/**\n * P5.5 — the agent host's reactor is a REMOTE attach: a running switchboard,\n * reached over GraphQL, instead of the embedded PGlite reactor glued to the\n * CLI's lifetime. N agents attach to ONE reactor as clients; the switchboard\n * outlives agent sessions. The agent DEPENDS on the switchboard — an\n * unreachable remote fails the attach loudly with the start hint, it never\n * auto-starts one.\n */\n\nexport interface AttachRemoteReactorOptions {\n /**\n * Where the switchboard lives: its GraphQL endpoint\n * (`http://localhost:4001/graphql`), a drive url (`…/d/<drive>`), or a bare\n * origin — the endpoint is derived.\n */\n url: string;\n /** Document models the client signs/reduces with. */\n documentModels: DocumentModelModule[];\n /**\n * What this agent expects of the fleet it joins (the host file's\n * reactor.protocol). Reachability and inspection facts are checked at\n * attach; flag-level comparison engages once the inspection subgraph\n * exposes the enforcement flags (upstream note in the phase-5 WBS) — until\n * then the expectation is carried for the error message and future use.\n */\n expectedProtocol?: ReactorProtocol;\n /** Bearer for authenticated switchboards; omitted = unauthenticated. */\n token?: string;\n /** Reachability probe budget. */\n timeoutMs?: number;\n}\n\nexport interface RemoteReactorAttachment {\n /** The derived GraphQL endpoint actually dialed. */\n endpoint: string;\n /** IReactorClient-compatible GraphQL client (reactor-browser). */\n client: unknown;\n /** Remote facts from the inspection subgraph, when it answers. */\n remoteInfo?: Record<string, unknown>;\n}\n\n/** Derive the GraphQL endpoint from the accepted url spellings. */\nexport function deriveGraphqlEndpoint(url: string): string {\n const parsed = new URL(url);\n if (parsed.pathname.includes(\"/d/\")) {\n return `${parsed.origin}/graphql`;\n }\n if (parsed.pathname.replace(/\\/$/, \"\").endsWith(\"/graphql\")) {\n return `${parsed.origin}${parsed.pathname.replace(/\\/$/, \"\")}`;\n }\n const base = parsed.pathname.replace(/\\/$/, \"\");\n return `${parsed.origin}${base}/graphql`;\n}\n\nasync function probeEndpoint(\n endpoint: string,\n timeoutMs: number,\n): Promise<void> {\n try {\n // A GraphQL endpoint answers POST; any HTTP response (even 400) proves\n // the server is listening. Only transport failure means unreachable.\n await fetch(endpoint, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ query: \"{ __typename }\" }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (cause) {\n throw new Error(\n `Cannot attach to the reactor at ${endpoint}: the switchboard is not ` +\n `answering. The agent depends on a RUNNING switchboard and never ` +\n `starts one — start it first (e.g. \\`ph run switchboard\\`, ` +\n `\\`ph vetra\\`, or the compound that members both) and retry.`,\n { cause },\n );\n }\n}\n\n/** Read the inspection subgraph's info when it answers (dev switchboards\n * under the OPEN policy serve it); absence is not an attach failure. */\nasync function readRemoteInfo(\n endpoint: string,\n token: string | undefined,\n timeoutMs: number,\n): Promise<Record<string, unknown> | undefined> {\n try {\n const res = await fetch(`${endpoint}/inspection`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(token ? { authorization: `Bearer ${token}` } : {}),\n },\n body: JSON.stringify({\n query: \"query ReactorInspectionInfo { inspection { info } }\",\n }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (!res.ok) return undefined;\n const body = (await res.json()) as {\n data?: { inspection?: { info?: Record<string, unknown> } };\n };\n return body.data?.inspection?.info;\n } catch {\n return undefined;\n }\n}\n\nexport async function attachRemoteReactor(\n options: AttachRemoteReactorOptions,\n): Promise<RemoteReactorAttachment> {\n const timeoutMs = options.timeoutMs ?? 10_000;\n const endpoint = deriveGraphqlEndpoint(options.url);\n\n await probeEndpoint(endpoint, timeoutMs);\n const remoteInfo = await readRemoteInfo(endpoint, options.token, timeoutMs);\n\n const { GraphQLReactorClient } =\n await import(\"@powerhousedao/reactor-browser/graphql-client\");\n const client = new GraphQLReactorClient({\n url: endpoint,\n documentModels: options.documentModels,\n ...(options.token\n ? { tokenProvider: () => Promise.resolve(options.token) }\n : {}),\n } as never);\n\n return { endpoint, client, remoteInfo };\n}\n","import { z } from \"zod\";\n\n/**\n * Read-only reactor tools for the agent host (mastra-runner). They wrap the\n * attached reactor client — the switchboard the host joined — so the model\n * can look at the fleet's documents instead of guessing: list drives, list a\n * drive's documents by type, read one document's state. Writes stay out: the\n * agent names the operation it would apply and a person applies it.\n *\n * The client is the IReactorClient-compatible GraphQL client from\n * `attachRemoteReactor`; only `find` and `get` are used, typed structurally so\n * this module does not pull the reactor packages into clint's graph.\n */\n\ninterface DocumentHeader {\n id: string;\n slug?: string;\n name?: string;\n documentType: string;\n createdAtUtcIso?: string;\n lastModifiedAtUtcIso?: string;\n revision?: Record<string, number>;\n}\n\ninterface DocumentLike {\n header: DocumentHeader;\n state: Record<string, unknown>;\n}\n\ninterface Paged<T> {\n results: T[];\n next?: () => Promise<Paged<T>>;\n}\n\nexport interface ReactorReadClient {\n find(\n search: { type?: string; parentId?: string },\n view?: undefined,\n paging?: { cursor: string; limit: number },\n ): Promise<Paged<DocumentLike>>;\n get(identifier: string): Promise<DocumentLike>;\n}\n\nexport interface ReactorReadToolsOptions {\n /** Cap on the serialized state a `getDocument` call returns (default 24k). */\n maxStateChars?: number;\n /** Cap on the documents one `listDocuments` call returns (default 200). */\n maxList?: number;\n}\n\nconst DRIVE_TYPE = \"powerhouse/document-drive\";\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/** The global scope's state, whichever way the client shaped `state`. */\nfunction globalState(doc: DocumentLike): Record<string, unknown> {\n const state = doc.state;\n if (isRecord(state.global)) return state.global;\n return state;\n}\n\n/**\n * A one-line view of a state object: its scalar fields, and the length of\n * each array field — enough to pick a document from a list without reading\n * every one.\n */\nexport function summarizeState(\n state: Record<string, unknown>,\n maxKeys = 16,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n let keys = 0;\n for (const [key, value] of Object.entries(state)) {\n if (keys >= maxKeys) break;\n if (value === null || value === undefined) continue;\n if (Array.isArray(value)) {\n out[`${key}Count`] = value.length;\n keys++;\n } else if (typeof value !== \"object\") {\n out[key] =\n typeof value === \"string\" && value.length > 120\n ? `${value.slice(0, 117)}…`\n : value;\n keys++;\n } else if (isRecord(value) && typeof value.name === \"string\") {\n // e.g. counterparty: { name }, submitter: { name }\n out[key] = value.name;\n keys++;\n }\n }\n return out;\n}\n\nfunction headerOf(doc: DocumentLike) {\n const h = doc.header;\n return {\n id: h.id,\n slug: h.slug ?? undefined,\n name: h.name ?? undefined,\n documentType: h.documentType,\n lastModified: h.lastModifiedAtUtcIso ?? undefined,\n };\n}\n\nasync function collect(\n first: Paged<DocumentLike>,\n max: number,\n): Promise<DocumentLike[]> {\n const out = [...first.results];\n let page = first;\n while (out.length < max && page.next && page.results.length > 0) {\n page = await page.next();\n out.push(...page.results);\n }\n return out.slice(0, max);\n}\n\nfunction truncateJson(\n value: unknown,\n maxChars: number,\n): {\n json: string;\n truncated: boolean;\n} {\n const json = JSON.stringify(value, null, 1);\n if (json.length <= maxChars) return { json, truncated: false };\n return { json: `${json.slice(0, maxChars)}…`, truncated: true };\n}\n\n/**\n * Build the Mastra tool set over an attached reactor client. Mastra is\n * imported lazily, like the rest of clint's Mastra integration.\n */\nexport async function createReactorReadTools(\n client: ReactorReadClient,\n options: ReactorReadToolsOptions = {},\n) {\n const { createTool } = await import(\"@mastra/core/tools\");\n const maxStateChars = options.maxStateChars ?? 24_000;\n const maxList = options.maxList ?? 200;\n\n const listDrives = createTool({\n id: \"listDrives\",\n description:\n \"List the drives on the reactor this agent is attached to: id, slug, \" +\n \"name and how many nodes (documents and folders) each holds. Call this \" +\n \"first when you do not know a drive id.\",\n inputSchema: z.object({}),\n execute: async () => {\n const page = await client.find({ type: DRIVE_TYPE }, undefined, {\n cursor: \"0\",\n limit: 100,\n });\n const drives = await collect(page, 100);\n return {\n drives: drives.map((d) => {\n const state = globalState(d);\n const nodes = Array.isArray(state.nodes) ? state.nodes.length : 0;\n return {\n ...headerOf(d),\n name:\n (typeof state.name === \"string\" && state.name) || d.header.name,\n nodeCount: nodes,\n };\n }),\n };\n },\n });\n\n const listDocuments = createTool({\n id: \"listDocuments\",\n description:\n \"List documents on the reactor, optionally within one drive (driveId) \" +\n \"and/or of one document type (e.g. sektar/invoice). Returns each \" +\n \"document's id, slug, name, type and a one-line summary of its state \" +\n \"(scalar fields plus array lengths). Use getDocument for the full state.\",\n inputSchema: z.object({\n driveId: z\n .string()\n .optional()\n .describe(\"Drive id to list within (from listDrives). Omit for all.\"),\n documentType: z\n .string()\n .optional()\n .describe(\"Document type to filter by, e.g. sektar/invoice.\"),\n limit: z\n .number()\n .int()\n .positive()\n .max(maxList)\n .optional()\n .describe(`Maximum documents to return (default 100, max ${maxList}).`),\n }),\n execute: async (input) => {\n const limit = Math.min(input.limit ?? 100, maxList);\n const page = await client.find(\n {\n ...(input.documentType ? { type: input.documentType } : {}),\n ...(input.driveId ? { parentId: input.driveId } : {}),\n },\n undefined,\n { cursor: \"0\", limit: Math.min(limit, 100) },\n );\n const docs = (await collect(page, limit)).filter(\n (d) => d.header.documentType !== DRIVE_TYPE || !!input.documentType,\n );\n return {\n count: docs.length,\n documents: docs.map((d) => ({\n ...headerOf(d),\n summary: summarizeState(globalState(d)),\n })),\n };\n },\n });\n\n const getDocument = createTool({\n id: \"getDocument\",\n description:\n \"Read one document by id or slug: its header and full global state as \" +\n \"JSON (truncated past a size cap; say so if `truncated` is true).\",\n inputSchema: z.object({\n identifier: z.string().describe(\"Document id or slug.\"),\n }),\n execute: async (input) => {\n const doc = await client.get(input.identifier);\n const { json, truncated } = truncateJson(globalState(doc), maxStateChars);\n return { ...headerOf(doc), state: json, truncated };\n },\n });\n\n return { listDrives, listDocuments, getDocument };\n}\n","import type { StreamChunk } from \"../core/types.js\";\n\n/**\n * The mastra-runner's provider seam: a real Mastra agent when a model is\n * configured, and a DEMO provider otherwise — same posture as the ph-rupert\n * example: the host answers without an API key, loudly saying it is the demo.\n */\nexport interface AgentStreamProvider {\n readonly modelId: string;\n stream(\n prompt: string,\n options: { threadId: string },\n ): AsyncIterable<StreamChunk>;\n}\n\nexport function createDemoProvider(agentName: string): AgentStreamProvider {\n return {\n modelId: \"demo\",\n // eslint-disable-next-line require-yield -- single-chunk generator below\n async *stream(prompt: string) {\n const text =\n `You said: ${JSON.stringify(prompt.slice(0, 2000))}. ` +\n `I'm the ${agentName} demo agent — configure a model (host config ` +\n `\\`model\\` and \\`apiKey\\`) for real responses.`;\n yield { type: \"text-delta\", text } as StreamChunk;\n },\n };\n}\n\nexport interface MastraProviderOptions {\n agentName: string;\n instructions: string;\n /** Mastra model-router string, e.g. `anthropic/claude-sonnet-4-5`. */\n model: string;\n /** The provider's API key (resolved host config). Absent: Mastra's model\n * router looks the provider's key up in the environment itself. */\n apiKey?: string;\n /** Tools the agent may call (Mastra `createTool` results), e.g. the\n * reactor read tools over the attached switchboard. */\n tools?: Record<string, unknown>;\n /** Tool-call rounds per turn; a framework knob (stays in code). */\n maxSteps?: number;\n}\n\n/** A model-router id names its provider: `<provider>/<model…>`. */\nfunction isRouterModelId(model: string): model is `${string}/${string}` {\n const slash = model.indexOf(\"/\");\n return slash > 0 && slash < model.length - 1;\n}\n\n/** Mastra's model config: the router id alone, or with an explicit key\n * (Mastra's OpenAI-compatible config object). */\nexport function mastraModelConfig(\n model: string,\n apiKey: string | undefined,\n): string | { id: `${string}/${string}`; apiKey: string } {\n if (apiKey === undefined) return model;\n if (!isRouterModelId(model)) {\n throw new Error(\n `model \"${model}\" is not a model-router id (\"<provider>/<model>\"), so an apiKey cannot be attached to it.`,\n );\n }\n return { id: model, apiKey };\n}\n\nexport async function createMastraProvider(\n options: MastraProviderOptions,\n): Promise<AgentStreamProvider> {\n const { Agent } = await import(\"@mastra/core/agent\");\n const { mapMastraStream } = await import(\"../integrations/mastra/stream.js\");\n const agent = new Agent({\n id: options.agentName,\n name: options.agentName,\n instructions: options.instructions,\n // With an apiKey the router uses it; without, it resolves the\n // provider's key from the environment.\n model: mastraModelConfig(options.model, options.apiKey),\n ...(options.tools ? { tools: options.tools as never } : {}),\n });\n return {\n modelId: options.model,\n async *stream(prompt: string, streamOptions: { threadId: string }) {\n const result = await agent.stream(prompt, {\n memory: undefined,\n threadId: streamOptions.threadId,\n maxSteps: options.maxSteps ?? 8,\n } as never);\n yield* mapMastraStream(\n (result as { fullStream: AsyncIterable<unknown> }).fullStream as never,\n );\n },\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport { createServer, type Server } from \"node:http\";\nimport {\n defaultUserDataDir,\n probeRun,\n resolveUserDataPlaceholders,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport {\n defineHostSchemas,\n switchboardOfDrive,\n} from \"@powerhousedao/host-core/schema\";\nimport { z } from \"zod\";\nimport {\n attachRemoteReactor,\n type RemoteReactorAttachment,\n} from \"../integrations/powerhouse/remote-reactor.js\";\nimport {\n createReactorReadTools,\n type ReactorReadClient,\n} from \"../integrations/powerhouse/reactor-tools.js\";\nimport {\n createDemoProvider,\n createMastraProvider,\n type AgentStreamProvider,\n} from \"./agent-provider.js\";\n\n/**\n * mastra-runner (P5.6): the headless agent host. Its reactor is a REMOTE\n * attach — a lone `remote` backend whose `remote.url` is a drive address on\n * the running switchboard (typically the output token\n * `switchboard.drives.powerhouse.url`, resolved before the verb runs); it\n * attaches to that switchboard's GraphQL endpoint, depends on it and never\n * starts one. `run`/`serve` expose an\n * OpenAI-compatible chat-completions endpoint (streaming SSE +\n * non-streaming, stateless baseline — the caller owns session state);\n * without a configured model it answers as the DEMO agent. `build` compiles\n * skills and agent profiles (ph-clint-dev's pipeline, ported).\n */\n\nexport const kind = \"reactor\";\n\n/** The verbs this runner exports (`promptFromMessages` is a helper). */\nexport const verbs = [\"run\", \"serve\", \"build\"] as const;\n\n/** The token a host writes for the switchboard's drive address (error hints). */\nconst REMOTE_URL_HINT =\n 'remote: { url: switchboard.drives.<slug>.url } (from ../switchboard/outputs.js), or literally { url: { $output: { host: \"switchboard\", path: [\"drives\", \"<slug>\", \"url\"] } } }';\n\n/**\n * The agent host, from one definition in two forms: DECLARED (`apiKey` may\n * be a token, e.g. `{ $env: \"OPENROUTER_API_KEY\" }`; what host.js authors\n * write) and RESOLVED (what the verbs receive).\n *\n * `config` holds OPERATOR SETTINGS only (rewire R5): `model` selects the\n * LLM, `apiKey` authenticates it, `instructions`/`prompts` shape the agent.\n * Framework KNOBS (maxSteps, cacheControl, memory tuning, untilIdle, tool\n * allowlists) stay in code, and the agent CARD (description/image) comes\n * from the host's `profile`, not here.\n */\nconst schemas = defineHostSchemas((s) => {\n const agentHostConfigSchema = z.strictObject({\n /** Mastra model router id (e.g. \"openrouter/<vendor>/<model>\"). Absent:\n * the runner answers as the demo agent. */\n model: z.string().min(1).optional(),\n /** The model provider's API key. A SECRET: write it as\n * `{ $env: \"OPENROUTER_API_KEY\" }` so it comes from the environment at\n * resolve time and never sits in the host file. Passed to the provider\n * as given; the runner does not read `process.env` itself. Absent, the\n * Mastra model router falls back to its own provider env lookup. */\n apiKey: s.tokenable(z.string().min(1)).optional(),\n instructions: z.string().optional(),\n /** `build`: skill + agent-profile compilation inputs and output. */\n prompts: z\n .strictObject({\n skillsDir: z.string().min(1).optional(),\n agentsDir: z.string().min(1).optional(),\n outDir: z.string().min(1).optional(),\n })\n .optional(),\n });\n /** `reactor` is the base block: a lone `remote` backend naming the\n * switchboard to attach to. `runner` takes no options beyond the base. */\n return s.reactorHostSchema.extend({\n runner: s.runnerBaseSchema.strict(),\n config: agentHostConfigSchema.optional(),\n });\n});\n/** Declared form: what a host file may contain before resolution. */\nexport const declaredHostSchema = schemas.declaredHostSchema;\n/** Resolved form: what the verbs receive (and `validateHost` checks). */\nexport const hostSchema = schemas.hostSchema;\n\n/** What an agent host.js author writes. */\nexport type MastraHostInput = z.input<typeof declaredHostSchema>;\n/** What the verbs receive. */\nexport type MastraHost = z.output<typeof hostSchema>;\nexport type AgentHostConfig = NonNullable<MastraHostInput[\"config\"]>;\n\n/** What serving the agent produces: where its OpenAI-compatible API is\n * actually bound. */\nexport const outputsSchema = z.strictObject({\n /** `http://<bound host>:<bound port>`. */\n origin: z.url(),\n endpoints: z.strictObject({\n /** OpenAI-compatible base URL (`<origin>/v1`). */\n openai: z.url(),\n /** Readiness probe (`<origin>/ready`). */\n ready: z.url(),\n }),\n});\n\nexport type MastraOutputs = z.infer<typeof outputsSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/clint/mastra-runner\": {\n host: MastraHostInput;\n outputs: MastraOutputs;\n };\n }\n}\n\nconst DEFAULT_AGENT_PORT = 4910;\n\n/** The GraphQL endpoint of the switchboard the remote backend's drive\n * address names, as resolved before the verb. */\nfunction remoteUrl(host: MastraHost): string {\n const backends = Object.values(host.reactor?.backends ?? {});\n const remote = backends.find((b) => b.kind === \"remote\");\n if (!remote) {\n throw new Error(\n `hosts/${host.name}: an agent host attaches to a RUNNING switchboard — ` +\n `declare a remote backend, e.g. reactor.backends.switchboard = ` +\n `{ kind: \"remote\", ${REMOTE_URL_HINT} }.`,\n );\n }\n const url = remote.remote?.url;\n const switchboard =\n typeof url === \"string\" ? switchboardOfDrive(url) : undefined;\n if (!switchboard) {\n throw new Error(\n `hosts/${host.name}: the remote backend needs a drive address on the ` +\n `switchboard (<switchboard>/d/<slug>): ${REMOTE_URL_HINT}.`,\n );\n }\n return switchboard.graphql;\n}\n\ntype ChatMessage = { role: string; content: unknown };\n\n/** Baseline stateless mapping: the last user message is the prompt (string\n * or OpenAI content-part arrays flattened to their text parts). */\nexport function promptFromMessages(messages: ChatMessage[]): string {\n const lastUser = [...messages].reverse().find((m) => m.role === \"user\");\n const content = lastUser?.content;\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n return content\n .map((part: { type?: string; text?: string }) =>\n part.type === \"text\" ? (part.text ?? \"\") : \"\",\n )\n .join(\"\");\n }\n return \"\";\n}\n\nasync function readBody(\n req: import(\"node:http\").IncomingMessage,\n): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction completionChunk(\n id: string,\n model: string,\n delta: Record<string, unknown>,\n finish: string | null,\n): string {\n return `data: ${JSON.stringify({\n id,\n object: \"chat.completion.chunk\",\n created: Math.floor(Date.now() / 1000),\n model,\n choices: [{ index: 0, delta, finish_reason: finish }],\n })}\\n\\n`;\n}\n\nexport type AgentServeHandle = RunnerHandle<MastraOutputs>;\n\nasync function serveAgent(\n host: MastraHost,\n ctx: RunnerContext,\n): Promise<AgentServeHandle> {\n const userData = defaultUserDataDir(ctx.projectRoot, ctx.env);\n const resolved = resolveUserDataPlaceholders(host, userData);\n const config = resolved.config ?? {};\n const port =\n typeof resolved.runner.port === \"number\"\n ? resolved.runner.port\n : DEFAULT_AGENT_PORT;\n\n // Single-instance lock: refuse before attaching or binding when the record\n // start-run wrote for a running instance of this host is live.\n const projectName = (() => {\n try {\n return (\n (\n JSON.parse(\n fs.readFileSync(`${ctx.projectRoot}/package.json`, \"utf8\"),\n ) as { name?: string }\n ).name ?? host.name\n );\n } catch {\n return host.name;\n }\n })();\n const probe = probeRun(ctx.projectRoot, resolved.name, projectName);\n if (probe.status === \"live\") {\n throw new Error(\n `${resolved.name} is already running (pid ${probe.record.pid}).`,\n );\n }\n\n // The reactor: attach, loudly, before serving anything.\n const attachment: RemoteReactorAttachment = await attachRemoteReactor({\n url: remoteUrl(resolved),\n documentModels: [],\n });\n console.log(`[${resolved.name}] reactor attached: ${attachment.endpoint}`);\n\n // The agent: real Mastra when a model is configured, demo otherwise. A real\n // agent gets read tools over the attached reactor (list drives, list\n // documents, read one) so it answers from the fleet's documents.\n let provider: AgentStreamProvider;\n if (config.model) {\n const tools = await createReactorReadTools(\n attachment.client as ReactorReadClient,\n );\n console.log(\n `[${resolved.name}] reactor tools: ${Object.keys(tools).join(\", \")}`,\n );\n provider = await createMastraProvider({\n agentName: resolved.name,\n instructions:\n config.instructions ??\n `You are ${resolved.name}, a Powerhouse project agent.`,\n model: config.model,\n apiKey: config.apiKey,\n tools,\n });\n } else {\n provider = createDemoProvider(resolved.name);\n }\n\n const server: Server = createServer((req, res) => {\n void (async () => {\n const url = (req.url ?? \"/\").split(\"?\")[0];\n if (req.method === \"GET\" && url === \"/ready\") {\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ ok: true, agent: resolved.name }));\n return;\n }\n if (req.method === \"GET\" && url === \"/v1/models\") {\n // The agent card: id + model, plus description/image from the host's\n // profile (rewire R5 — identity lives in profile, not config).\n const profile = resolved.profile ?? {};\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(\n JSON.stringify({\n object: \"list\",\n data: [\n {\n id: provider.modelId,\n object: \"model\",\n owned_by: \"clint\",\n name: profile.name ?? resolved.name,\n ...(profile.description\n ? { description: profile.description }\n : {}),\n ...(profile.icon ? { image: profile.icon } : {}),\n },\n ],\n }),\n );\n return;\n }\n if (req.method === \"POST\" && url === \"/v1/chat/completions\") {\n let body: { messages?: ChatMessage[]; stream?: boolean };\n try {\n body = JSON.parse(await readBody(req)) as typeof body;\n } catch {\n res.writeHead(400, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ error: { message: \"invalid JSON body\" } }));\n return;\n }\n const prompt = promptFromMessages(body.messages ?? []);\n const id = `chatcmpl-${randomUUID()}`;\n const threadId = randomUUID(); // stateless baseline: the caller owns sessions\n\n if (body.stream) {\n res.writeHead(200, {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-store\",\n connection: \"keep-alive\",\n });\n res.write(\n completionChunk(id, provider.modelId, { role: \"assistant\" }, null),\n );\n try {\n for await (const chunk of provider.stream(prompt, { threadId })) {\n if (chunk.type === \"text-delta\" && chunk.text) {\n res.write(\n completionChunk(\n id,\n provider.modelId,\n { content: chunk.text },\n null,\n ),\n );\n } else if (chunk.type === \"error\") {\n res.write(\n completionChunk(\n id,\n provider.modelId,\n {\n content: `\\n[agent error] ${String((chunk as { message?: unknown }).message ?? \"unknown\")}`,\n },\n null,\n ),\n );\n }\n }\n res.write(completionChunk(id, provider.modelId, {}, \"stop\"));\n res.write(\"data: [DONE]\\n\\n\");\n } finally {\n res.end();\n }\n return;\n }\n\n let text = \"\";\n for await (const chunk of provider.stream(prompt, { threadId })) {\n if (chunk.type === \"text-delta\" && chunk.text) text += chunk.text;\n }\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id,\n object: \"chat.completion\",\n created: Math.floor(Date.now() / 1000),\n model: provider.modelId,\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: text },\n finish_reason: \"stop\",\n },\n ],\n }),\n );\n return;\n }\n res.writeHead(404, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ error: { message: `no route: ${url}` } }));\n })().catch((error: unknown) => {\n if (!res.headersSent) res.writeHead(500);\n res.end(JSON.stringify({ error: { message: String(error) } }));\n });\n });\n\n const ready = new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(port, \"127.0.0.1\", () => resolve());\n });\n await ready;\n // The actual bound port (a requested 0 means \"any free port\").\n const boundPort = (server.address() as { port: number }).port;\n const origin = `http://127.0.0.1:${boundPort}`;\n const outputs = outputsSchema.parse({\n origin,\n endpoints: { openai: `${origin}/v1`, ready: `${origin}/ready` },\n });\n console.log(\n `[${resolved.name}] agent API (OpenAI-compatible): ${outputs.endpoints.openai} (model: ${provider.modelId})`,\n );\n\n // No run record here: standalone `ph run` (start-run) publishes `outputs`\n // in the v2 record because this module exports `outputsSchema`, and a\n // compound records its members itself. One writer per record.\n return {\n outputs,\n ready,\n shutdown: async () => {\n await new Promise((resolve) => server.close(resolve));\n },\n };\n}\n\nexport async function run(\n host: MastraHost,\n ctx: RunnerContext,\n): Promise<AgentServeHandle> {\n return serveAgent(host, ctx);\n}\n\nexport const serve = run;\n\n/** `build` — skill + agent-profile compilation (ph-clint-dev's pipeline). */\nexport async function build(\n host: MastraHost,\n ctx: RunnerContext,\n): Promise<void> {\n const config = host.config ?? {};\n const { buildSkills } = await import(\"../dev/build-skills.js\");\n const result = await buildSkills({\n rootDir: ctx.projectRoot,\n skillsDir: config.prompts?.skillsDir,\n agentsDir: config.prompts?.agentsDir,\n outDir: config.prompts?.outDir,\n });\n console.log(\n `[${host.name}] compiled ${result.skills} skill(s), ${result.profiles} profile(s) → ${result.outDir}`,\n );\n}\n"],"mappings":";;;;;;;;AA6CA,SAAgB,sBAAsB,KAAqB;CACzD,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,IAAI,OAAO,SAAS,SAAS,KAAK,GAChC,OAAO,GAAG,OAAO,OAAO;CAE1B,IAAI,OAAO,SAAS,QAAQ,OAAO,EAAE,CAAC,CAAC,SAAS,UAAU,GACxD,OAAO,GAAG,OAAO,SAAS,OAAO,SAAS,QAAQ,OAAO,EAAE;CAE7D,MAAM,OAAO,OAAO,SAAS,QAAQ,OAAO,EAAE;CAC9C,OAAO,GAAG,OAAO,SAAS,KAAK;AACjC;AAEA,eAAe,cACb,UACA,WACe;CACf,IAAI;EAGF,MAAM,MAAM,UAAU;GACpB,QAAQ;GACR,SAAS,EAAE,gBAAgB,mBAAmB;GAC9C,MAAM,KAAK,UAAU,EAAE,OAAO,iBAAiB,CAAC;GAChD,QAAQ,YAAY,QAAQ,SAAS;EACvC,CAAC;CACH,SAAS,OAAO;EACd,MAAM,IAAI,MACR,mCAAmC,SAAS,iNAI5C,EAAE,MAAM,CACV;CACF;AACF;;;AAIA,eAAe,eACb,UACA,OACA,WAC8C;CAC9C,IAAI;EACF,MAAM,MAAM,MAAM,MAAM,GAAG,SAAS,cAAc;GAChD,QAAQ;GACR,SAAS;IACP,gBAAgB;IAChB,GAAI,QAAQ,EAAE,eAAe,UAAU,QAAQ,IAAI,CAAC;GACtD;GACA,MAAM,KAAK,UAAU,EACnB,OAAO,sDACT,CAAC;GACD,QAAQ,YAAY,QAAQ,SAAS;EACvC,CAAC;EACD,IAAI,CAAC,IAAI,IAAI,OAAO,KAAA;E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AAU,YAAY;GACpB,MAAM,IAAI,SAAS,YAAY,OAAO,MAAM,OAAO,CAAC;EACtD;CACF;AACF;AAEA,eAAsB,IACpB,MACA,KAC2B;CAC3B,OAAO,WAAW,MAAM,GAAG;AAC7B;AAEA,MAAa,QAAQ;;AAGrB,eAAsB,MACpB,MACA,KACe;CACf,MAAM,SAAS,KAAK,UAAU,CAAC;CAC/B,MAAM,EAAE,gBAAgB,MAAM,OAAO;CACrC,MAAM,SAAS,MAAM,YAAY;EAC/B,SAAS,IAAI;EACb,WAAW,OAAO,SAAS;EAC3B,WAAW,OAAO,SAAS;EAC3B,QAAQ,OAAO,SAAS;CAC1B,CAAC;CACD,QAAQ,IACN,IAAI,KAAK,KAAK,aAAa,OAAO,OAAO,aAAa,OAAO,SAAS,gBAAgB,OAAO,QAC/F;AACF"}
1
+ {"version":3,"file":"mastra-runner.mjs","names":[],"sources":["../../src/integrations/powerhouse/reactor-tools.ts","../../src/runners/agent-provider.ts","../../src/runners/mastra-runner.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/**\n * Read-only reactor tools for the agent host (mastra-runner). They wrap the\n * attached reactor client — the switchboard the host joined — so the model\n * can look at the fleet's documents instead of guessing: list drives, list a\n * drive's documents by type, read one document's state. Writes stay out: the\n * agent names the operation it would apply and a person applies it.\n *\n * The client is the IReactorClient-compatible GraphQL client from\n * `attachRemoteReactor`; only `find` and `get` are used, typed structurally so\n * this module does not pull the reactor packages into clint's graph.\n */\n\ninterface DocumentHeader {\n id: string;\n slug?: string;\n name?: string;\n documentType: string;\n createdAtUtcIso?: string;\n lastModifiedAtUtcIso?: string;\n revision?: Record<string, number>;\n}\n\ninterface DocumentLike {\n header: DocumentHeader;\n state: Record<string, unknown>;\n}\n\ninterface Paged<T> {\n results: T[];\n next?: () => Promise<Paged<T>>;\n}\n\nexport interface ReactorReadClient {\n find(\n search: { type?: string; parentId?: string },\n view?: undefined,\n paging?: { cursor: string; limit: number },\n ): Promise<Paged<DocumentLike>>;\n get(identifier: string): Promise<DocumentLike>;\n}\n\nexport interface ReactorReadToolsOptions {\n /** Cap on the serialized state a `getDocument` call returns (default 24k). */\n maxStateChars?: number;\n /** Cap on the documents one `listDocuments` call returns (default 200). */\n maxList?: number;\n}\n\nconst DRIVE_TYPE = \"powerhouse/document-drive\";\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/** The global scope's state, whichever way the client shaped `state`. */\nfunction globalState(doc: DocumentLike): Record<string, unknown> {\n const state = doc.state;\n if (isRecord(state.global)) return state.global;\n return state;\n}\n\n/**\n * A one-line view of a state object: its scalar fields, and the length of\n * each array field — enough to pick a document from a list without reading\n * every one.\n */\nexport function summarizeState(\n state: Record<string, unknown>,\n maxKeys = 16,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n let keys = 0;\n for (const [key, value] of Object.entries(state)) {\n if (keys >= maxKeys) break;\n if (value === null || value === undefined) continue;\n if (Array.isArray(value)) {\n out[`${key}Count`] = value.length;\n keys++;\n } else if (typeof value !== \"object\") {\n out[key] =\n typeof value === \"string\" && value.length > 120\n ? `${value.slice(0, 117)}…`\n : value;\n keys++;\n } else if (isRecord(value) && typeof value.name === \"string\") {\n // e.g. counterparty: { name }, submitter: { name }\n out[key] = value.name;\n keys++;\n }\n }\n return out;\n}\n\nfunction headerOf(doc: DocumentLike) {\n const h = doc.header;\n return {\n id: h.id,\n slug: h.slug ?? undefined,\n name: h.name ?? undefined,\n documentType: h.documentType,\n lastModified: h.lastModifiedAtUtcIso ?? undefined,\n };\n}\n\nasync function collect(\n first: Paged<DocumentLike>,\n max: number,\n): Promise<DocumentLike[]> {\n const out = [...first.results];\n let page = first;\n while (out.length < max && page.next && page.results.length > 0) {\n page = await page.next();\n out.push(...page.results);\n }\n return out.slice(0, max);\n}\n\nfunction truncateJson(\n value: unknown,\n maxChars: number,\n): {\n json: string;\n truncated: boolean;\n} {\n const json = JSON.stringify(value, null, 1);\n if (json.length <= maxChars) return { json, truncated: false };\n return { json: `${json.slice(0, maxChars)}…`, truncated: true };\n}\n\n/**\n * Build the Mastra tool set over an attached reactor client. Mastra is\n * imported lazily, like the rest of clint's Mastra integration.\n */\nexport async function createReactorReadTools(\n client: ReactorReadClient,\n options: ReactorReadToolsOptions = {},\n) {\n const { createTool } = await import(\"@mastra/core/tools\");\n const maxStateChars = options.maxStateChars ?? 24_000;\n const maxList = options.maxList ?? 200;\n\n const listDrives = createTool({\n id: \"listDrives\",\n description:\n \"List the drives on the reactor this agent is attached to: id, slug, \" +\n \"name and how many nodes (documents and folders) each holds. Call this \" +\n \"first when you do not know a drive id.\",\n inputSchema: z.object({}),\n execute: async () => {\n const page = await client.find({ type: DRIVE_TYPE }, undefined, {\n cursor: \"0\",\n limit: 100,\n });\n const drives = await collect(page, 100);\n return {\n drives: drives.map((d) => {\n const state = globalState(d);\n const nodes = Array.isArray(state.nodes) ? state.nodes.length : 0;\n return {\n ...headerOf(d),\n name:\n (typeof state.name === \"string\" && state.name) || d.header.name,\n nodeCount: nodes,\n };\n }),\n };\n },\n });\n\n const listDocuments = createTool({\n id: \"listDocuments\",\n description:\n \"List documents on the reactor, optionally within one drive (driveId) \" +\n \"and/or of one document type (e.g. sektar/invoice). Returns each \" +\n \"document's id, slug, name, type and a one-line summary of its state \" +\n \"(scalar fields plus array lengths). Use getDocument for the full state.\",\n inputSchema: z.object({\n driveId: z\n .string()\n .optional()\n .describe(\"Drive id to list within (from listDrives). Omit for all.\"),\n documentType: z\n .string()\n .optional()\n .describe(\"Document type to filter by, e.g. sektar/invoice.\"),\n limit: z\n .number()\n .int()\n .positive()\n .max(maxList)\n .optional()\n .describe(`Maximum documents to return (default 100, max ${maxList}).`),\n }),\n execute: async (input) => {\n const limit = Math.min(input.limit ?? 100, maxList);\n const page = await client.find(\n {\n ...(input.documentType ? { type: input.documentType } : {}),\n ...(input.driveId ? { parentId: input.driveId } : {}),\n },\n undefined,\n { cursor: \"0\", limit: Math.min(limit, 100) },\n );\n const docs = (await collect(page, limit)).filter(\n (d) => d.header.documentType !== DRIVE_TYPE || !!input.documentType,\n );\n return {\n count: docs.length,\n documents: docs.map((d) => ({\n ...headerOf(d),\n summary: summarizeState(globalState(d)),\n })),\n };\n },\n });\n\n const getDocument = createTool({\n id: \"getDocument\",\n description:\n \"Read one document by id or slug: its header and full global state as \" +\n \"JSON (truncated past a size cap; say so if `truncated` is true).\",\n inputSchema: z.object({\n identifier: z.string().describe(\"Document id or slug.\"),\n }),\n execute: async (input) => {\n const doc = await client.get(input.identifier);\n const { json, truncated } = truncateJson(globalState(doc), maxStateChars);\n return { ...headerOf(doc), state: json, truncated };\n },\n });\n\n return { listDrives, listDocuments, getDocument };\n}\n","import type { StreamChunk } from \"../core/types.js\";\n\n/**\n * The mastra-runner's provider seam: a real Mastra agent when a model is\n * configured, and a DEMO provider otherwise — same posture as the ph-rupert\n * example: the host answers without an API key, loudly saying it is the demo.\n */\nexport interface AgentStreamProvider {\n readonly modelId: string;\n stream(\n prompt: string,\n options: { threadId: string },\n ): AsyncIterable<StreamChunk>;\n}\n\nexport function createDemoProvider(agentName: string): AgentStreamProvider {\n return {\n modelId: \"demo\",\n // eslint-disable-next-line require-yield -- single-chunk generator below\n async *stream(prompt: string) {\n const text =\n `You said: ${JSON.stringify(prompt.slice(0, 2000))}. ` +\n `I'm the ${agentName} demo agent — configure a model (host config ` +\n `\\`model\\` and \\`apiKey\\`) for real responses.`;\n yield { type: \"text-delta\", text } as StreamChunk;\n },\n };\n}\n\nexport interface MastraProviderOptions {\n agentName: string;\n instructions: string;\n /** Mastra model-router string, e.g. `anthropic/claude-sonnet-4-5`. */\n model: string;\n /** The provider's API key (resolved host config). Absent: Mastra's model\n * router looks the provider's key up in the environment itself. */\n apiKey?: string;\n /** Tools the agent may call (Mastra `createTool` results), e.g. the\n * reactor read tools over the attached switchboard. */\n tools?: Record<string, unknown>;\n /** Tool-call rounds per turn; a framework knob (stays in code). */\n maxSteps?: number;\n}\n\n/** A model-router id names its provider: `<provider>/<model…>`. */\nfunction isRouterModelId(model: string): model is `${string}/${string}` {\n const slash = model.indexOf(\"/\");\n return slash > 0 && slash < model.length - 1;\n}\n\n/** Mastra's model config: the router id alone, or with an explicit key\n * (Mastra's OpenAI-compatible config object). */\nexport function mastraModelConfig(\n model: string,\n apiKey: string | undefined,\n): string | { id: `${string}/${string}`; apiKey: string } {\n if (apiKey === undefined) return model;\n if (!isRouterModelId(model)) {\n throw new Error(\n `model \"${model}\" is not a model-router id (\"<provider>/<model>\"), so an apiKey cannot be attached to it.`,\n );\n }\n return { id: model, apiKey };\n}\n\nexport async function createMastraProvider(\n options: MastraProviderOptions,\n): Promise<AgentStreamProvider> {\n const { Agent } = await import(\"@mastra/core/agent\");\n const { mapMastraStream } = await import(\"../integrations/mastra/stream.js\");\n const agent = new Agent({\n id: options.agentName,\n name: options.agentName,\n instructions: options.instructions,\n // With an apiKey the router uses it; without, it resolves the\n // provider's key from the environment.\n model: mastraModelConfig(options.model, options.apiKey),\n ...(options.tools ? { tools: options.tools as never } : {}),\n });\n return {\n modelId: options.model,\n async *stream(prompt: string, streamOptions: { threadId: string }) {\n const result = await agent.stream(prompt, {\n memory: undefined,\n threadId: streamOptions.threadId,\n maxSteps: options.maxSteps ?? 8,\n } as never);\n yield* mapMastraStream(\n (result as { fullStream: AsyncIterable<unknown> }).fullStream as never,\n );\n },\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport { createServer, type Server } from \"node:http\";\nimport {\n defaultUserDataDir,\n probeRun,\n resolveUserDataPlaceholders,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport {\n defineHostSchemas,\n switchboardOfDrive,\n} from \"@powerhousedao/host-core/schema\";\nimport { z } from \"zod\";\nimport {\n attachRemoteReactor,\n type RemoteReactorAttachment,\n} from \"../integrations/powerhouse/remote-reactor.js\";\nimport {\n createReactorReadTools,\n type ReactorReadClient,\n} from \"../integrations/powerhouse/reactor-tools.js\";\nimport {\n createDemoProvider,\n createMastraProvider,\n type AgentStreamProvider,\n} from \"./agent-provider.js\";\n\n/**\n * mastra-runner (P5.6): the headless agent host. Its reactor is a REMOTE\n * attach — a lone `remote` backend whose `remote.url` is a drive address on\n * the running switchboard (typically the output token\n * `switchboard.drives.powerhouse.url`, resolved before the verb runs); it\n * attaches to that switchboard's GraphQL endpoint, depends on it and never\n * starts one. `run`/`serve` expose an\n * OpenAI-compatible chat-completions endpoint (streaming SSE +\n * non-streaming, stateless baseline — the caller owns session state);\n * without a configured model it answers as the DEMO agent. `build` compiles\n * skills and agent profiles (ph-clint-dev's pipeline, ported).\n */\n\nexport const kind = \"reactor\";\n\n/** The verbs this runner exports (`promptFromMessages` is a helper). */\nexport const verbs = [\"run\", \"serve\", \"build\"] as const;\n\n/** The token a host writes for the switchboard's drive address (error hints). */\nconst REMOTE_URL_HINT =\n 'remote: { url: switchboard.drives.<slug>.url } (from ../switchboard/outputs.js), or literally { url: { $output: { host: \"switchboard\", path: [\"drives\", \"<slug>\", \"url\"] } } }';\n\n/**\n * The agent host, from one definition in two forms: DECLARED (`apiKey` may\n * be a token, e.g. `{ $env: \"OPENROUTER_API_KEY\" }`; what host.js authors\n * write) and RESOLVED (what the verbs receive).\n *\n * `config` holds OPERATOR SETTINGS only (rewire R5): `model` selects the\n * LLM, `apiKey` authenticates it, `instructions`/`prompts` shape the agent.\n * Framework KNOBS (maxSteps, cacheControl, memory tuning, untilIdle, tool\n * allowlists) stay in code, and the agent CARD (description/image) comes\n * from the host's `profile`, not here.\n */\nconst schemas = defineHostSchemas((s) => {\n const agentHostConfigSchema = z.strictObject({\n /** Mastra model router id (e.g. \"openrouter/<vendor>/<model>\"). Absent:\n * the runner answers as the demo agent. */\n model: z.string().min(1).optional(),\n /** The model provider's API key. A SECRET: write it as\n * `{ $env: \"OPENROUTER_API_KEY\" }` so it comes from the environment at\n * resolve time and never sits in the host file. Passed to the provider\n * as given; the runner does not read `process.env` itself. Absent, the\n * Mastra model router falls back to its own provider env lookup. */\n apiKey: s.tokenable(z.string().min(1)).optional(),\n instructions: z.string().optional(),\n /** `build`: skill + agent-profile compilation inputs and output. */\n prompts: z\n .strictObject({\n skillsDir: z.string().min(1).optional(),\n agentsDir: z.string().min(1).optional(),\n outDir: z.string().min(1).optional(),\n })\n .optional(),\n });\n /** `reactor` is the base block: a lone `remote` backend naming the\n * switchboard to attach to. `runner` takes no options beyond the base. */\n return s.reactorHostSchema.extend({\n runner: s.runnerBaseSchema.strict(),\n config: agentHostConfigSchema.optional(),\n });\n});\n/** Declared form: what a host file may contain before resolution. */\nexport const declaredHostSchema = schemas.declaredHostSchema;\n/** Resolved form: what the verbs receive (and `validateHost` checks). */\nexport const hostSchema = schemas.hostSchema;\n\n/** What an agent host.js author writes. */\nexport type MastraHostInput = z.input<typeof declaredHostSchema>;\n/** What the verbs receive. */\nexport type MastraHost = z.output<typeof hostSchema>;\nexport type AgentHostConfig = NonNullable<MastraHostInput[\"config\"]>;\n\n/** What serving the agent produces: where its OpenAI-compatible API is\n * actually bound. */\nexport const outputsSchema = z.strictObject({\n /** `http://<bound host>:<bound port>`. */\n origin: z.url(),\n endpoints: z.strictObject({\n /** OpenAI-compatible base URL (`<origin>/v1`). */\n openai: z.url(),\n /** Readiness probe (`<origin>/ready`). */\n ready: z.url(),\n }),\n});\n\nexport type MastraOutputs = z.infer<typeof outputsSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/clint/mastra-runner\": {\n host: MastraHostInput;\n outputs: MastraOutputs;\n };\n }\n}\n\nconst DEFAULT_AGENT_PORT = 4910;\n\n/** The GraphQL endpoint of the switchboard the remote backend's drive\n * address names, as resolved before the verb. */\nfunction remoteUrl(host: MastraHost): string {\n const backends = Object.values(host.reactor?.backends ?? {});\n const remote = backends.find((b) => b.kind === \"remote\");\n if (!remote) {\n throw new Error(\n `hosts/${host.name}: an agent host attaches to a RUNNING switchboard — ` +\n `declare a remote backend, e.g. reactor.backends.switchboard = ` +\n `{ kind: \"remote\", ${REMOTE_URL_HINT} }.`,\n );\n }\n const url = remote.remote?.url;\n const switchboard =\n typeof url === \"string\" ? switchboardOfDrive(url) : undefined;\n if (!switchboard) {\n throw new Error(\n `hosts/${host.name}: the remote backend needs a drive address on the ` +\n `switchboard (<switchboard>/d/<slug>): ${REMOTE_URL_HINT}.`,\n );\n }\n return switchboard.graphql;\n}\n\ntype ChatMessage = { role: string; content: unknown };\n\n/** Baseline stateless mapping: the last user message is the prompt (string\n * or OpenAI content-part arrays flattened to their text parts). */\nexport function promptFromMessages(messages: ChatMessage[]): string {\n const lastUser = [...messages].reverse().find((m) => m.role === \"user\");\n const content = lastUser?.content;\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n return content\n .map((part: { type?: string; text?: string }) =>\n part.type === \"text\" ? (part.text ?? \"\") : \"\",\n )\n .join(\"\");\n }\n return \"\";\n}\n\nasync function readBody(\n req: import(\"node:http\").IncomingMessage,\n): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction completionChunk(\n id: string,\n model: string,\n delta: Record<string, unknown>,\n finish: string | null,\n): string {\n return `data: ${JSON.stringify({\n id,\n object: \"chat.completion.chunk\",\n created: Math.floor(Date.now() / 1000),\n model,\n choices: [{ index: 0, delta, finish_reason: finish }],\n })}\\n\\n`;\n}\n\nexport type AgentServeHandle = RunnerHandle<MastraOutputs>;\n\nasync function serveAgent(\n host: MastraHost,\n ctx: RunnerContext,\n): Promise<AgentServeHandle> {\n const userData = defaultUserDataDir(ctx.projectRoot, ctx.env);\n const resolved = resolveUserDataPlaceholders(host, userData);\n const config = resolved.config ?? {};\n const port =\n typeof resolved.runner.port === \"number\"\n ? resolved.runner.port\n : DEFAULT_AGENT_PORT;\n\n // Single-instance lock: refuse before attaching or binding when the record\n // start-run wrote for a running instance of this host is live.\n const projectName = (() => {\n try {\n return (\n (\n JSON.parse(\n fs.readFileSync(`${ctx.projectRoot}/package.json`, \"utf8\"),\n ) as { name?: string }\n ).name ?? host.name\n );\n } catch {\n return host.name;\n }\n })();\n const probe = probeRun(ctx.projectRoot, resolved.name, projectName);\n if (probe.status === \"live\") {\n throw new Error(\n `${resolved.name} is already running (pid ${probe.record.pid}).`,\n );\n }\n\n // The reactor: attach, loudly, before serving anything.\n const attachment: RemoteReactorAttachment = await attachRemoteReactor({\n url: remoteUrl(resolved),\n documentModels: [],\n });\n console.log(`[${resolved.name}] reactor attached: ${attachment.endpoint}`);\n\n // The agent: real Mastra when a model is configured, demo otherwise. A real\n // agent gets read tools over the attached reactor (list drives, list\n // documents, read one) so it answers from the fleet's documents.\n let provider: AgentStreamProvider;\n if (config.model) {\n const tools = await createReactorReadTools(\n attachment.client as ReactorReadClient,\n );\n console.log(\n `[${resolved.name}] reactor tools: ${Object.keys(tools).join(\", \")}`,\n );\n provider = await createMastraProvider({\n agentName: resolved.name,\n instructions:\n config.instructions ??\n `You are ${resolved.name}, a Powerhouse project agent.`,\n model: config.model,\n apiKey: config.apiKey,\n tools,\n });\n } else {\n provider = createDemoProvider(resolved.name);\n }\n\n const server: Server = createServer((req, res) => {\n void (async () => {\n const url = (req.url ?? \"/\").split(\"?\")[0];\n if (req.method === \"GET\" && url === \"/ready\") {\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ ok: true, agent: resolved.name }));\n return;\n }\n if (req.method === \"GET\" && url === \"/v1/models\") {\n // The agent card: id + model, plus description/image from the host's\n // profile (rewire R5 — identity lives in profile, not config).\n const profile = resolved.profile ?? {};\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(\n JSON.stringify({\n object: \"list\",\n data: [\n {\n id: provider.modelId,\n object: \"model\",\n owned_by: \"clint\",\n name: profile.name ?? resolved.name,\n ...(profile.description\n ? { description: profile.description }\n : {}),\n ...(profile.icon ? { image: profile.icon } : {}),\n },\n ],\n }),\n );\n return;\n }\n if (req.method === \"POST\" && url === \"/v1/chat/completions\") {\n let body: { messages?: ChatMessage[]; stream?: boolean };\n try {\n body = JSON.parse(await readBody(req)) as typeof body;\n } catch {\n res.writeHead(400, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ error: { message: \"invalid JSON body\" } }));\n return;\n }\n const prompt = promptFromMessages(body.messages ?? []);\n const id = `chatcmpl-${randomUUID()}`;\n const threadId = randomUUID(); // stateless baseline: the caller owns sessions\n\n if (body.stream) {\n res.writeHead(200, {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-store\",\n connection: \"keep-alive\",\n });\n res.write(\n completionChunk(id, provider.modelId, { role: \"assistant\" }, null),\n );\n try {\n for await (const chunk of provider.stream(prompt, { threadId })) {\n if (chunk.type === \"text-delta\" && chunk.text) {\n res.write(\n completionChunk(\n id,\n provider.modelId,\n { content: chunk.text },\n null,\n ),\n );\n } else if (chunk.type === \"error\") {\n res.write(\n completionChunk(\n id,\n provider.modelId,\n {\n content: `\\n[agent error] ${String((chunk as { message?: unknown }).message ?? \"unknown\")}`,\n },\n null,\n ),\n );\n }\n }\n res.write(completionChunk(id, provider.modelId, {}, \"stop\"));\n res.write(\"data: [DONE]\\n\\n\");\n } finally {\n res.end();\n }\n return;\n }\n\n let text = \"\";\n for await (const chunk of provider.stream(prompt, { threadId })) {\n if (chunk.type === \"text-delta\" && chunk.text) text += chunk.text;\n }\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id,\n object: \"chat.completion\",\n created: Math.floor(Date.now() / 1000),\n model: provider.modelId,\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: text },\n finish_reason: \"stop\",\n },\n ],\n }),\n );\n return;\n }\n res.writeHead(404, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ error: { message: `no route: ${url}` } }));\n })().catch((error: unknown) => {\n if (!res.headersSent) res.writeHead(500);\n res.end(JSON.stringify({ error: { message: String(error) } }));\n });\n });\n\n const ready = new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(port, \"127.0.0.1\", () => resolve());\n });\n await ready;\n // The actual bound port (a requested 0 means \"any free port\").\n const boundPort = (server.address() as { port: number }).port;\n const origin = `http://127.0.0.1:${boundPort}`;\n const outputs = outputsSchema.parse({\n origin,\n endpoints: { openai: `${origin}/v1`, ready: `${origin}/ready` },\n });\n console.log(\n `[${resolved.name}] agent API (OpenAI-compatible): ${outputs.endpoints.openai} (model: ${provider.modelId})`,\n );\n\n // No run record here: standalone `ph run` (start-run) publishes `outputs`\n // in the v2 record because this module exports `outputsSchema`, and a\n // compound records its members itself. One writer per record.\n return {\n outputs,\n ready,\n shutdown: async () => {\n await new Promise((resolve) => server.close(resolve));\n },\n };\n}\n\nexport async function run(\n host: MastraHost,\n ctx: RunnerContext,\n): Promise<AgentServeHandle> {\n return serveAgent(host, ctx);\n}\n\nexport const serve = run;\n\n/**\n * `build` — skill + agent-profile compilation (ph-clint-dev's pipeline).\n * When the package also exports a `Cli` (`./cli`), its metadata joins the\n * template context; without that export the build is path-driven only.\n */\nexport async function build(\n host: MastraHost,\n ctx: RunnerContext,\n): Promise<void> {\n const config = host.config ?? {};\n const { buildSkills } = await import(\"../dev/build-skills.js\");\n const { loadOwnCli } = await import(\"./cli-runner.js\");\n const result = await buildSkills({\n rootDir: ctx.projectRoot,\n cli: await loadOwnCli(ctx.projectRoot),\n skillsDir: config.prompts?.skillsDir,\n agentsDir: config.prompts?.agentsDir,\n outDir: config.prompts?.outDir,\n });\n console.log(\n `[${host.name}] compiled ${result.skills} skill(s), ${result.profiles} profile(s) → ${result.outDir}`,\n );\n}\n"],"mappings":";;;;;;;;AAkDA,MAAM,aAAa;AAEnB,SAAS,SAAS,GAA0C;CAC1D,OAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAChE;;AAGA,SAAS,YAAY,KAA4C;CAC/D,MAAM,QAAQ,IAAI;CAClB,IAAI,SAAS,MAAM,MAAM,GAAG,OAAO,MAAM;CAC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/runners/proxy-runner.d.ts
4
+ /**
5
+ * proxy-runner (A7): the same-origin proxy as a member of a generic compound.
6
+ * One front port routes to upstream URLs, WebSocket-aware, over the clint
7
+ * package's createProxyServer. A route to a sibling member names that member
8
+ * host's own output (`upstream: switchboard.origin`, or `{ $output: { host:
9
+ * "switchboard", path: ["origin"] } }`): the compound resolves it from the
10
+ * members started before the proxy, so the proxy starts after them, and
11
+ * stops before them. The routes are fixed at start. The Cli in front reads
12
+ * the proxy's address from its outputs (`proxy.url`), as any member's.
13
+ */
14
+ export declare const kind = "reactor";
15
+ /** The verbs this runner exports. `build` is no work: it lets a compound
16
+ * forward one `build` verb to every member. */
17
+ export declare const verbs: readonly ["run", "serve", "dev", "build"];
18
+ /** Declared form: what a host file may contain before resolution. */
19
+ export declare const declaredHostSchema: z.ZodObject<{
20
+ name: z.ZodString;
21
+ profile: z.ZodOptional<z.ZodObject<{
22
+ appId: z.ZodOptional<z.ZodString>;
23
+ name: z.ZodOptional<z.ZodString>;
24
+ description: z.ZodOptional<z.ZodString>;
25
+ icon: z.ZodOptional<z.ZodString>;
26
+ }, z.core.$strict>>;
27
+ reactor: z.ZodOptional<z.ZodObject<{
28
+ backends: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
29
+ kind: z.ZodEnum<{
30
+ "in-process": "in-process";
31
+ remote: "remote";
32
+ worker: "worker";
33
+ }>;
34
+ storage: z.ZodOptional<z.ZodObject<{
35
+ kind: z.ZodEnum<{
36
+ idb: "idb";
37
+ memory: "memory";
38
+ path: "path";
39
+ postgres: "postgres";
40
+ }>;
41
+ dataDir: z.ZodOptional<import("@powerhousedao/host-core").TokenableSchema<z.ZodString, import("@powerhousedao/host-core").EnvToken>>;
42
+ url: z.ZodOptional<z.ZodString>;
43
+ }, z.core.$strict>>;
44
+ readModel: z.ZodOptional<z.ZodObject<{
45
+ url: z.ZodOptional<z.ZodString>;
46
+ }, z.core.$strict>>;
47
+ packages: z.ZodOptional<z.ZodObject<{
48
+ cdnUrl: z.ZodOptional<z.ZodString>;
49
+ specs: z.ZodOptional<z.ZodArray<z.ZodString>>;
50
+ dynamic: z.ZodOptional<z.ZodBoolean>;
51
+ }, z.core.$strict>>;
52
+ remote: z.ZodOptional<z.ZodObject<{
53
+ url: import("@powerhousedao/host-core").TokenableSchema<z.ZodUnion<readonly [z.ZodURL, z.ZodString]>>;
54
+ requestTimeoutMs: z.ZodOptional<z.ZodNumber>;
55
+ breaker: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<false>, z.ZodObject<{
56
+ failures: z.ZodOptional<z.ZodNumber>;
57
+ openMs: z.ZodOptional<z.ZodNumber>;
58
+ }, z.core.$strict>]>>;
59
+ realtime: z.ZodOptional<z.ZodBoolean>;
60
+ }, z.core.$strict>>;
61
+ }, z.core.$strict>>>;
62
+ placement: z.ZodOptional<z.ZodObject<{
63
+ primary: z.ZodOptional<z.ZodString>;
64
+ drives: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
65
+ newDrives: z.ZodOptional<z.ZodString>;
66
+ }, z.core.$strict>>;
67
+ router: z.ZodOptional<z.ZodObject<{
68
+ probeTimeoutMs: z.ZodOptional<z.ZodNumber>;
69
+ provisionalRouteMs: z.ZodOptional<z.ZodNumber>;
70
+ }, z.core.$strict>>;
71
+ protocol: z.ZodOptional<z.ZodObject<{
72
+ featureFlags: z.ZodOptional<z.ZodObject<{
73
+ documentDecisions: z.ZodOptional<z.ZodBoolean>;
74
+ authEnforcement: z.ZodOptional<z.ZodBoolean>;
75
+ authGroups: z.ZodOptional<z.ZodBoolean>;
76
+ authConditions: z.ZodOptional<z.ZodBoolean>;
77
+ undoV3: z.ZodOptional<z.ZodBoolean>;
78
+ }, z.core.$strict>>;
79
+ createSignaturePolicy: z.ZodOptional<z.ZodEnum<{
80
+ legacy: "legacy";
81
+ "v2-required": "v2-required";
82
+ }>>;
83
+ unsupportedStoredDocuments: z.ZodOptional<z.ZodEnum<{
84
+ "read-only": "read-only";
85
+ refuse: "refuse";
86
+ }>>;
87
+ }, z.core.$strict>>;
88
+ renown: z.ZodOptional<z.ZodObject<{
89
+ url: z.ZodOptional<z.ZodString>;
90
+ networkId: z.ZodOptional<z.ZodString>;
91
+ chainId: z.ZodOptional<z.ZodNumber>;
92
+ }, z.core.$strict>>;
93
+ namespace: z.ZodOptional<z.ZodString>;
94
+ drives: z.ZodOptional<import("@powerhousedao/host-core").TokenableSchema<z.ZodArray<z.ZodObject<{
95
+ slug: z.ZodString;
96
+ id: z.ZodOptional<z.ZodString>;
97
+ projectHash: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodLiteral<"id">]>>;
98
+ documentType: z.ZodOptional<z.ZodEnum<{
99
+ "powerhouse/document-drive": "powerhouse/document-drive";
100
+ "powerhouse/reactor-drive": "powerhouse/reactor-drive";
101
+ }>>;
102
+ name: z.ZodOptional<z.ZodString>;
103
+ icon: z.ZodOptional<z.ZodString>;
104
+ preferredEditor: z.ZodOptional<z.ZodString>;
105
+ sharingType: z.ZodOptional<z.ZodEnum<{
106
+ private: "private";
107
+ public: "public";
108
+ shared: "shared";
109
+ }>>;
110
+ availableOffline: z.ZodOptional<z.ZodBoolean>;
111
+ remote: z.ZodOptional<z.ZodObject<{
112
+ url: import("@powerhousedao/host-core").TokenableSchema<z.ZodString>;
113
+ }, z.core.$strict>>;
114
+ }, z.core.$strict>>>>;
115
+ }, z.core.$strict>>;
116
+ runner: z.ZodObject<{
117
+ module: z.ZodString;
118
+ defaultVerb: z.ZodOptional<z.ZodString>;
119
+ host: z.ZodOptional<z.ZodString>;
120
+ plugins: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
121
+ module: z.ZodString;
122
+ enabled: z.ZodOptional<z.ZodBoolean>;
123
+ verbs: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"*">, z.ZodArray<z.ZodString>]>>;
124
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
125
+ }, z.core.$strict>]>>>;
126
+ port: z.ZodOptional<z.ZodNumber>;
127
+ }, z.core.$strict>;
128
+ config: z.ZodObject<{
129
+ publicUrl: z.ZodOptional<z.ZodURL>;
130
+ routes: z.ZodRecord<z.ZodString, z.ZodObject<{
131
+ upstream: import("@powerhousedao/host-core").TokenableSchema<z.ZodURL>;
132
+ path: z.ZodOptional<z.ZodString>;
133
+ ws: z.ZodOptional<z.ZodBoolean>;
134
+ }, z.core.$strict>>;
135
+ }, z.core.$strict>;
136
+ }, z.core.$strict>;
137
+ /** Resolved form: what the verbs receive (and `validateHost` checks). */
138
+ export declare const hostSchema: z.ZodObject<{
139
+ name: z.ZodString;
140
+ profile: z.ZodOptional<z.ZodObject<{
141
+ appId: z.ZodOptional<z.ZodString>;
142
+ name: z.ZodOptional<z.ZodString>;
143
+ description: z.ZodOptional<z.ZodString>;
144
+ icon: z.ZodOptional<z.ZodString>;
145
+ }, z.core.$strict>>;
146
+ reactor: z.ZodOptional<z.ZodObject<{
147
+ backends: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
148
+ kind: z.ZodEnum<{
149
+ "in-process": "in-process";
150
+ remote: "remote";
151
+ worker: "worker";
152
+ }>;
153
+ storage: z.ZodOptional<z.ZodObject<{
154
+ kind: z.ZodEnum<{
155
+ idb: "idb";
156
+ memory: "memory";
157
+ path: "path";
158
+ postgres: "postgres";
159
+ }>;
160
+ dataDir: z.ZodOptional<import("@powerhousedao/host-core").TokenableSchema<z.ZodString, import("@powerhousedao/host-core").EnvToken>>;
161
+ url: z.ZodOptional<z.ZodString>;
162
+ }, z.core.$strict>>;
163
+ readModel: z.ZodOptional<z.ZodObject<{
164
+ url: z.ZodOptional<z.ZodString>;
165
+ }, z.core.$strict>>;
166
+ packages: z.ZodOptional<z.ZodObject<{
167
+ cdnUrl: z.ZodOptional<z.ZodString>;
168
+ specs: z.ZodOptional<z.ZodArray<z.ZodString>>;
169
+ dynamic: z.ZodOptional<z.ZodBoolean>;
170
+ }, z.core.$strict>>;
171
+ remote: z.ZodOptional<z.ZodObject<{
172
+ url: import("@powerhousedao/host-core").TokenableSchema<z.ZodUnion<readonly [z.ZodURL, z.ZodString]>>;
173
+ requestTimeoutMs: z.ZodOptional<z.ZodNumber>;
174
+ breaker: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<false>, z.ZodObject<{
175
+ failures: z.ZodOptional<z.ZodNumber>;
176
+ openMs: z.ZodOptional<z.ZodNumber>;
177
+ }, z.core.$strict>]>>;
178
+ realtime: z.ZodOptional<z.ZodBoolean>;
179
+ }, z.core.$strict>>;
180
+ }, z.core.$strict>>>;
181
+ placement: z.ZodOptional<z.ZodObject<{
182
+ primary: z.ZodOptional<z.ZodString>;
183
+ drives: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
184
+ newDrives: z.ZodOptional<z.ZodString>;
185
+ }, z.core.$strict>>;
186
+ router: z.ZodOptional<z.ZodObject<{
187
+ probeTimeoutMs: z.ZodOptional<z.ZodNumber>;
188
+ provisionalRouteMs: z.ZodOptional<z.ZodNumber>;
189
+ }, z.core.$strict>>;
190
+ protocol: z.ZodOptional<z.ZodObject<{
191
+ featureFlags: z.ZodOptional<z.ZodObject<{
192
+ documentDecisions: z.ZodOptional<z.ZodBoolean>;
193
+ authEnforcement: z.ZodOptional<z.ZodBoolean>;
194
+ authGroups: z.ZodOptional<z.ZodBoolean>;
195
+ authConditions: z.ZodOptional<z.ZodBoolean>;
196
+ undoV3: z.ZodOptional<z.ZodBoolean>;
197
+ }, z.core.$strict>>;
198
+ createSignaturePolicy: z.ZodOptional<z.ZodEnum<{
199
+ legacy: "legacy";
200
+ "v2-required": "v2-required";
201
+ }>>;
202
+ unsupportedStoredDocuments: z.ZodOptional<z.ZodEnum<{
203
+ "read-only": "read-only";
204
+ refuse: "refuse";
205
+ }>>;
206
+ }, z.core.$strict>>;
207
+ renown: z.ZodOptional<z.ZodObject<{
208
+ url: z.ZodOptional<z.ZodString>;
209
+ networkId: z.ZodOptional<z.ZodString>;
210
+ chainId: z.ZodOptional<z.ZodNumber>;
211
+ }, z.core.$strict>>;
212
+ namespace: z.ZodOptional<z.ZodString>;
213
+ drives: z.ZodOptional<import("@powerhousedao/host-core").TokenableSchema<z.ZodArray<z.ZodObject<{
214
+ slug: z.ZodString;
215
+ id: z.ZodOptional<z.ZodString>;
216
+ projectHash: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodLiteral<"id">]>>;
217
+ documentType: z.ZodOptional<z.ZodEnum<{
218
+ "powerhouse/document-drive": "powerhouse/document-drive";
219
+ "powerhouse/reactor-drive": "powerhouse/reactor-drive";
220
+ }>>;
221
+ name: z.ZodOptional<z.ZodString>;
222
+ icon: z.ZodOptional<z.ZodString>;
223
+ preferredEditor: z.ZodOptional<z.ZodString>;
224
+ sharingType: z.ZodOptional<z.ZodEnum<{
225
+ private: "private";
226
+ public: "public";
227
+ shared: "shared";
228
+ }>>;
229
+ availableOffline: z.ZodOptional<z.ZodBoolean>;
230
+ remote: z.ZodOptional<z.ZodObject<{
231
+ url: import("@powerhousedao/host-core").TokenableSchema<z.ZodString>;
232
+ }, z.core.$strict>>;
233
+ }, z.core.$strict>>>>;
234
+ }, z.core.$strict>>;
235
+ runner: z.ZodObject<{
236
+ module: z.ZodString;
237
+ defaultVerb: z.ZodOptional<z.ZodString>;
238
+ host: z.ZodOptional<z.ZodString>;
239
+ plugins: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
240
+ module: z.ZodString;
241
+ enabled: z.ZodOptional<z.ZodBoolean>;
242
+ verbs: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"*">, z.ZodArray<z.ZodString>]>>;
243
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
244
+ }, z.core.$strict>]>>>;
245
+ port: z.ZodOptional<z.ZodNumber>;
246
+ }, z.core.$strict>;
247
+ config: z.ZodObject<{
248
+ publicUrl: z.ZodOptional<z.ZodURL>;
249
+ routes: z.ZodRecord<z.ZodString, z.ZodObject<{
250
+ upstream: import("@powerhousedao/host-core").TokenableSchema<z.ZodURL>;
251
+ path: z.ZodOptional<z.ZodString>;
252
+ ws: z.ZodOptional<z.ZodBoolean>;
253
+ }, z.core.$strict>>;
254
+ }, z.core.$strict>;
255
+ }, z.core.$strict>;
256
+ /** What a proxy host.js author writes. */
257
+ export type ProxyHostInput = z.input<typeof declaredHostSchema>;
258
+ /** What the verbs receive. */
259
+ export type ProxyHost = z.output<typeof hostSchema>;
260
+ /** What starting the proxy produces: its address (the `publicUrl` when set). */
261
+ export declare const outputsSchema: z.ZodObject<{
262
+ url: z.ZodURL;
263
+ }, z.core.$strict>;
264
+ export type ProxyOutputs = z.infer<typeof outputsSchema>;
265
+ declare global {
266
+ interface PHHostRunners {
267
+ "@powerhousedao/clint/proxy-runner": {
268
+ host: ProxyHostInput;
269
+ outputs: ProxyOutputs;
270
+ };
271
+ }
272
+ }
273
+ export type ProxyHandle = RunnerHandle<ProxyOutputs>;
274
+ export declare function run(host: ProxyHost, _ctx: RunnerContext): Promise<ProxyHandle>;
275
+ export declare const serve: typeof run;
276
+ export declare const dev: typeof run;
277
+ /** Nothing to build. */
278
+ export declare function build(): Promise<void>;
279
+ //#endregion
280
+ export {};
281
+ //# sourceMappingURL=proxy-runner.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxy-runner.d.mts","names":[],"sources":["../../src/runners/proxy-runner.ts"],"mappings":";;;;;;;;;;;;;qBAgBa;;;qBAIA;;qBAgCA,oBAAkB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAA6B,EAAA,KAAA;;qBAE/C,YAAU,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAAqB,EAAA,KAAA;;YAGhC,iBAAiB,EAAE,aAAa;;YAEhC,YAAY,EAAE,cAAc;;qBAG3B,eAAa,EAAA;;GAExB,EAAA,KAAA;YAEU,eAAe,EAAE,aAAa;QAElC;YACI;IACR;MACE,MAAM;MACN,SAAS;;;;YAKH,cAAc,aAAa;wBAEjB,IACpB,MAAM,WACN,MAAM,gBACL,QAAQ;qBA4BE,cAAK;qBACL,YAAG;;wBAGM,SAAS"}
@@ -0,0 +1,91 @@
1
+ import { z } from "zod";
2
+ import { defineHostSchemas } from "@powerhousedao/host-core/schema";
3
+ //#region src/runners/proxy-route-table.ts
4
+ /** Pure route-table assembly: each upstream, trailing slashes trimmed, plus
5
+ * its optional path. */
6
+ function buildProxyRouteTable(routes) {
7
+ return Object.entries(routes).map(([prefix, route]) => ({
8
+ prefix,
9
+ upstream: `${route.upstream.replace(/\/+$/, "")}${route.path ?? ""}`,
10
+ ws: route.ws ?? false,
11
+ source: `upstream:${route.upstream}`
12
+ }));
13
+ }
14
+ //#endregion
15
+ //#region src/runners/proxy-runner.ts
16
+ /**
17
+ * proxy-runner (A7): the same-origin proxy as a member of a generic compound.
18
+ * One front port routes to upstream URLs, WebSocket-aware, over the clint
19
+ * package's createProxyServer. A route to a sibling member names that member
20
+ * host's own output (`upstream: switchboard.origin`, or `{ $output: { host:
21
+ * "switchboard", path: ["origin"] } }`): the compound resolves it from the
22
+ * members started before the proxy, so the proxy starts after them, and
23
+ * stops before them. The routes are fixed at start. The Cli in front reads
24
+ * the proxy's address from its outputs (`proxy.url`), as any member's.
25
+ */
26
+ const kind = "reactor";
27
+ /** The verbs this runner exports. `build` is no work: it lets a compound
28
+ * forward one `build` verb to every member. */
29
+ const verbs = [
30
+ "run",
31
+ "serve",
32
+ "dev",
33
+ "build"
34
+ ];
35
+ /**
36
+ * The proxy host, from one definition in two forms: DECLARED (an upstream
37
+ * may be an output token; what host.js authors write) and RESOLVED (what the
38
+ * verbs receive). `runner.port` is the front port (0 = any free port) and
39
+ * `runner.host` the bind address. The default is "127.0.0.1": a container or
40
+ * cloud host sets "0.0.0.0" in its own host data.
41
+ */
42
+ const schemas = defineHostSchemas((s) => s.reactorHostSchema.extend({
43
+ runner: s.runnerBaseSchema.extend({ port: z.number().int().min(0).max(65535).optional() }).strict(),
44
+ config: z.strictObject({
45
+ /** Browser-facing base URL when the proxy sits behind an ingress. */
46
+ publicUrl: z.url().optional(),
47
+ /** Route prefix -> target: an upstream URL, an optional path and ws. */
48
+ routes: z.record(z.string(), z.strictObject({
49
+ upstream: s.tokenable(z.url()),
50
+ path: z.string().optional(),
51
+ ws: z.boolean().optional()
52
+ }))
53
+ })
54
+ }));
55
+ /** Declared form: what a host file may contain before resolution. */
56
+ const declaredHostSchema = schemas.declaredHostSchema;
57
+ /** Resolved form: what the verbs receive (and `validateHost` checks). */
58
+ const hostSchema = schemas.hostSchema;
59
+ /** What starting the proxy produces: its address (the `publicUrl` when set). */
60
+ const outputsSchema = z.strictObject({ url: z.url() });
61
+ async function run(host, _ctx) {
62
+ const table = buildProxyRouteTable(host.config.routes);
63
+ const { createProxyServer } = await import("../proxy-ji3EHzLn.mjs").then((n) => n.n);
64
+ const instance = await createProxyServer({
65
+ port: host.runner.port ?? 0,
66
+ host: host.runner.host ?? "127.0.0.1",
67
+ publicUrl: host.config.publicUrl,
68
+ logger: console
69
+ });
70
+ for (const route of table) instance.addRoute({
71
+ prefix: route.prefix,
72
+ upstream: new URL(route.upstream),
73
+ ws: route.ws,
74
+ source: route.source
75
+ });
76
+ console.log(`[${host.name}] proxy listening on ${instance.url} — ${table.length} route(s)`);
77
+ let stopping;
78
+ return {
79
+ outputs: outputsSchema.parse({ url: instance.url }),
80
+ ready: Promise.resolve(),
81
+ shutdown: () => stopping ??= instance.stop()
82
+ };
83
+ }
84
+ const serve = run;
85
+ const dev = run;
86
+ /** Nothing to build. */
87
+ async function build() {}
88
+ //#endregion
89
+ export { build, declaredHostSchema, dev, hostSchema, kind, outputsSchema, run, serve, verbs };
90
+
91
+ //# sourceMappingURL=proxy-runner.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxy-runner.mjs","names":[],"sources":["../../src/runners/proxy-route-table.ts","../../src/runners/proxy-runner.ts"],"sourcesContent":["/* Kept out of proxy-runner.ts: a runner module exports only its verb\n * functions (plus schemas and constants). */\n\n/** One declared route of a proxy host, resolved (its upstream a URL). */\nexport interface ProxyRouteInput {\n upstream: string;\n path?: string;\n ws?: boolean;\n}\n\n/** A route as the proxy server takes it. */\nexport interface ResolvedProxyRoute {\n prefix: string;\n upstream: string;\n ws: boolean;\n source: string;\n}\n\n/** Pure route-table assembly: each upstream, trailing slashes trimmed, plus\n * its optional path. */\nexport function buildProxyRouteTable(\n routes: Record<string, ProxyRouteInput>,\n): ResolvedProxyRoute[] {\n return Object.entries(routes).map(([prefix, route]) => ({\n prefix,\n upstream: `${route.upstream.replace(/\\/+$/, \"\")}${route.path ?? \"\"}`,\n ws: route.ws ?? false,\n source: `upstream:${route.upstream}`,\n }));\n}\n","import type { RunnerContext, RunnerHandle } from \"@powerhousedao/host-core\";\nimport { defineHostSchemas } from \"@powerhousedao/host-core/schema\";\nimport { z } from \"zod\";\nimport { buildProxyRouteTable } from \"./proxy-route-table.js\";\n\n/**\n * proxy-runner (A7): the same-origin proxy as a member of a generic compound.\n * One front port routes to upstream URLs, WebSocket-aware, over the clint\n * package's createProxyServer. A route to a sibling member names that member\n * host's own output (`upstream: switchboard.origin`, or `{ $output: { host:\n * \"switchboard\", path: [\"origin\"] } }`): the compound resolves it from the\n * members started before the proxy, so the proxy starts after them, and\n * stops before them. The routes are fixed at start. The Cli in front reads\n * the proxy's address from its outputs (`proxy.url`), as any member's.\n */\n\nexport const kind = \"reactor\";\n\n/** The verbs this runner exports. `build` is no work: it lets a compound\n * forward one `build` verb to every member. */\nexport const verbs = [\"run\", \"serve\", \"dev\", \"build\"] as const;\n\n/**\n * The proxy host, from one definition in two forms: DECLARED (an upstream\n * may be an output token; what host.js authors write) and RESOLVED (what the\n * verbs receive). `runner.port` is the front port (0 = any free port) and\n * `runner.host` the bind address. The default is \"127.0.0.1\": a container or\n * cloud host sets \"0.0.0.0\" in its own host data.\n */\nconst schemas = defineHostSchemas((s) =>\n s.reactorHostSchema.extend({\n runner: s.runnerBaseSchema\n .extend({\n port: z.number().int().min(0).max(65535).optional(),\n })\n .strict(),\n config: z.strictObject({\n /** Browser-facing base URL when the proxy sits behind an ingress. */\n publicUrl: z.url().optional(),\n /** Route prefix -> target: an upstream URL, an optional path and ws. */\n routes: z.record(\n z.string(),\n z.strictObject({\n upstream: s.tokenable(z.url()),\n path: z.string().optional(),\n ws: z.boolean().optional(),\n }),\n ),\n }),\n }),\n);\n/** Declared form: what a host file may contain before resolution. */\nexport const declaredHostSchema = schemas.declaredHostSchema;\n/** Resolved form: what the verbs receive (and `validateHost` checks). */\nexport const hostSchema = schemas.hostSchema;\n\n/** What a proxy host.js author writes. */\nexport type ProxyHostInput = z.input<typeof declaredHostSchema>;\n/** What the verbs receive. */\nexport type ProxyHost = z.output<typeof hostSchema>;\n\n/** What starting the proxy produces: its address (the `publicUrl` when set). */\nexport const outputsSchema = z.strictObject({\n url: z.url(),\n});\n\nexport type ProxyOutputs = z.infer<typeof outputsSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/clint/proxy-runner\": {\n host: ProxyHostInput;\n outputs: ProxyOutputs;\n };\n }\n}\n\nexport type ProxyHandle = RunnerHandle<ProxyOutputs>;\n\nexport async function run(\n host: ProxyHost,\n _ctx: RunnerContext,\n): Promise<ProxyHandle> {\n const table = buildProxyRouteTable(host.config.routes);\n const { createProxyServer } = await import(\"../core/proxy.js\");\n const instance = await createProxyServer({\n port: host.runner.port ?? 0,\n host: host.runner.host ?? \"127.0.0.1\",\n publicUrl: host.config.publicUrl,\n logger: console as never,\n });\n for (const route of table) {\n instance.addRoute({\n prefix: route.prefix,\n upstream: new URL(route.upstream),\n ws: route.ws,\n source: route.source,\n });\n }\n console.log(\n `[${host.name}] proxy listening on ${instance.url} — ${table.length} route(s)`,\n );\n let stopping: Promise<void> | undefined;\n return {\n outputs: outputsSchema.parse({ url: instance.url }),\n ready: Promise.resolve(),\n shutdown: () => (stopping ??= instance.stop()),\n };\n}\n\nexport const serve = run;\nexport const dev = run;\n\n/** Nothing to build. */\nexport async function build(): Promise<void> {}\n"],"mappings":";;;;;AAoBA,SAAgB,qBACd,QACsB;CACtB,OAAO,OAAO,QAAQ,MAAM,CAAC,CAAC,KAAK,CAAC,QAAQ,YAAY;EACtD;EACA,UAAU,GAAG,MAAM,SAAS,QAAQ,QAAQ,EAAE,IAAI,MAAM,QAAQ;EAChE,IAAI,MAAM,MAAM;EAChB,QAAQ,YAAY,MAAM;CAC5B,EAAE;AACJ;;;;;;;;;;;;;ACbA,MAAa,OAAO;;;AAIpB,MAAa,QAAQ;CAAC;CAAO;CAAS;CAAO;AAAO;;;;;;;;AASpD,MAAM,UAAU,mBAAmB,MACjC,EAAE,kBAAkB,OAAO;CACzB,QAAQ,EAAE,iBACP,OAAO,EACN,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,SAAS,EACpD,CAAC,CAAC,CACD,OAAO;CACV,QAAQ,EAAE,aAAa;;EAErB,WAAW,EAAE,IAAI,CAAC,CAAC,SAAS;;EAE5B,QAAQ,EAAE,OACR,EAAE,OAAO,GACT,EAAE,aAAa;GACb,UAAU,EAAE,UAAU,EAAE,IAAI,CAAC;GAC7B,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS;GAC1B,IAAI,EAAE,QAAQ,CAAC,CAAC,SAAS;EAC3B,CAAC,CACH;CACF,CAAC;AACH,CAAC,CACH;;AAEA,MAAa,qBAAqB,QAAQ;;AAE1C,MAAa,aAAa,QAAQ;;AAQlC,MAAa,gBAAgB,EAAE,aAAa,EAC1C,KAAK,EAAE,IAAI,EACb,CAAC;AAeD,eAAsB,IACpB,MACA,MACsB;CACtB,MAAM,QAAQ,qBAAqB,KAAK,OAAO,MAAM;CACrD,MAAM,EAAE,sBAAsB,MAAM,OAAO,wBAAmB,CAAA,MAAA,MAAA,EAAA,CAAA;CAC9D,MAAM,WAAW,MAAM,kBAAkB;EACvC,MAAM,KAAK,OAAO,QAAQ;EAC1B,MAAM,KAAK,OAAO,QAAQ;EAC1B,WAAW,KAAK,OAAO;EACvB,QAAQ;CACV,CAAC;CACD,KAAK,MAAM,SAAS,OAClB,SAAS,SAAS;EAChB,QAAQ,MAAM;EACd,UAAU,IAAI,IAAI,MAAM,QAAQ;EAChC,IAAI,MAAM;EACV,QAAQ,MAAM;CAChB,CAAC;CAEH,QAAQ,IACN,IAAI,KAAK,KAAK,uBAAuB,SAAS,IAAI,KAAK,MAAM,OAAO,UACtE;CACA,IAAI;CACJ,OAAO;EACL,SAAS,cAAc,MAAM,EAAE,KAAK,SAAS,IAAI,CAAC;EAClD,OAAO,QAAQ,QAAQ;EACvB,gBAAiB,aAAa,SAAS,KAAK;CAC9C;AACF;AAEA,MAAa,QAAQ;AACrB,MAAa,MAAM;;AAGnB,eAAsB,QAAuB,CAAC"}
@@ -0,0 +1,47 @@
1
+ import { z } from "zod";
2
+ //#region src/core/schema.ts
3
+ const WRAPPER_TYPES = /* @__PURE__ */ new Set([
4
+ "default",
5
+ "optional",
6
+ "nullable"
7
+ ]);
8
+ /**
9
+ * Extract field entries from a ZodObject schema's shape.
10
+ * Returns an empty array for non-object schemas.
11
+ *
12
+ * When `sensitiveKeys` is provided, those fields are marked `sensitive: true`.
13
+ */
14
+ function getSchemaFields(schema, sensitiveKeys) {
15
+ if (!(schema instanceof z.ZodObject)) return [];
16
+ const fields = [];
17
+ for (const [key, field] of Object.entries(schema.shape)) fields.push({
18
+ key,
19
+ description: field.description,
20
+ isOptional: field.isOptional(),
21
+ hasDefault: field instanceof z.ZodDefault,
22
+ defaultValue: field instanceof z.ZodDefault ? field.def.defaultValue : void 0,
23
+ baseType: resolveBaseType(field),
24
+ sensitive: sensitiveKeys?.has(key) ?? false
25
+ });
26
+ return fields;
27
+ }
28
+ /**
29
+ * Resolve the base type name by unwrapping Default/Optional/Nullable wrappers.
30
+ * Uses .type and .def.innerType (both public Zod v4 API).
31
+ */
32
+ function resolveBaseType(schema) {
33
+ let current = schema;
34
+ while (WRAPPER_TYPES.has(current.type) && current.def.innerType) current = current.def.innerType;
35
+ return current.type;
36
+ }
37
+ /**
38
+ * Convert a kebab-case slug to a Title Case string.
39
+ * E.g. 'document-modeling' → 'Document Modeling'
40
+ */
41
+ function slugToTitle(slug) {
42
+ return slug.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
43
+ }
44
+ //#endregion
45
+ export { slugToTitle as n, getSchemaFields as t };
46
+
47
+ //# sourceMappingURL=schema-BEKAZGyT.mjs.map