@powerhousedao/ph-cli 6.2.3-dev.85 → 6.2.3-dev.86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -297,6 +297,27 @@ module.exports = {
297
297
  };
298
298
  ```
299
299
 
300
+ ## Catch-up and telemetry output
301
+
302
+ While a reactor catches up, `ph vetra` and `ph switchboard` show progress below the server's output. With processor timing on (see `PH_PROCESSOR_TIMING` in the deployment docs) they also list the busiest processors of the last minute, and one summary when catch-up ends. Without a terminal, the same comes as log lines:
303
+
304
+ ```
305
+ catch-up: sektar (8 drives) 47% · vetra (10 drives) 0% · priority 4 dynamic
306
+ catch-up slowest (60 s): FilesIndex·files 41s (handler 12s read 25s fill 4.1s) 3.1k op/s eta 59s · SearchIndex·mail 9.8s (handler 8.9s read 0.6s fill 0.3s) 410 op/s
307
+ catch-up done in 4m12s; slowest since start: FilesIndex·files 2m01s · SearchIndex·mail 38s
308
+ ```
309
+
310
+ With `console` in `PH_MEMORY_TELEMETRY_OUTPUT`, a memory line comes through stderr every five minutes:
311
+
312
+ ```
313
+ memory: rss 4.12 GB (+61 MB/min) · heap 2.35 GB, post-GC 2.10 GB (+49 MB/min) · pglite 3.60 GB · 1830 ops/30s, 17 MB/1k ops · top: processors.bufferedLiveOps +2.9k/min
314
+ ```
315
+
316
+ | Variable | Meaning | Default |
317
+ | ---------------------- | ------------------------------------------------------------- | ------- |
318
+ | `PH_CATCH_UP_PROGRESS` | `false` turns all of this output off, the memory line as well | _unset_ |
319
+ | `PH_CATCH_UP_TOP` | How many of the slowest processors to list; `0` hides them | `5` |
320
+
300
321
  ## Troubleshooting
301
322
 
302
323
  ### Common Issues
@@ -1,7 +1,7 @@
1
1
 
2
- !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]="8c7ada8c-f4b9-5527-bc5f-8a7110589167")}catch(e){}}();
2
+ !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]="85160053-9251-5dc4-810b-78262a363f93")}catch(e){}}();
3
3
  import { n as checkHost } from "./dist-BfUgk19n.mjs";
4
- import { s as rememberShellNames } from "./member-config-BShHC35u.mjs";
4
+ import { s as rememberShellNames } from "./member-config-CLziqSGm.mjs";
5
5
  import path from "node:path";
6
6
  import { envNamesBeforeProjectEnv, loadProjectEnv } from "@powerhousedao/shared/clis/project-env";
7
7
  import dotenv from "dotenv";
@@ -52,5 +52,5 @@ async function runHostCheck(args) {
52
52
  //#endregion
53
53
  export { runHostCheck };
54
54
 
55
- //# sourceMappingURL=check-BWRbBScq.mjs.map
56
- //# debugId=8c7ada8c-f4b9-5527-bc5f-8a7110589167
55
+ //# sourceMappingURL=check-o9kpHrG_.mjs.map
56
+ //# debugId=85160053-9251-5dc4-810b-78262a363f93
@@ -1 +1 @@
1
- {"version":3,"file":"check-BWRbBScq.mjs","sources":["../src/services/host/check.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { checkHost, type HostIssue } from \"@powerhousedao/host-core\";\nimport { CALLER_CWD_ENV } from \"@powerhousedao/shared/clis/command-names\";\nimport {\n envNamesBeforeProjectEnv,\n loadProjectEnv,\n} from \"@powerhousedao/shared/clis/project-env\";\nimport dotenv from \"dotenv\";\nimport { rememberShellNames } from \"../../runners/member-config.js\";\n\nexport interface HostCheckArgs {\n host: string;\n envFile?: string;\n verb?: string;\n projectRoot?: string;\n}\n\n/** Without `envFile`: what `ph run` sees (project .env under process env). */\nasync function checkEnv(\n projectRoot: string,\n envFile: string | undefined,\n): Promise<Record<string, string | undefined>> {\n if (envFile === undefined) {\n loadProjectEnv(projectRoot);\n // A snapshot: a .env a runner's checkBoot loads later never reaches it.\n const env = { ...process.env };\n // The switchboard's checkBoot puts the .env's values under the host file.\n rememberShellNames(env, envNamesBeforeProjectEnv() ?? Object.keys(env));\n return env;\n }\n const from = process.env[CALLER_CWD_ENV] ?? process.cwd();\n try {\n return dotenv.parse(await readFile(path.resolve(from, envFile), \"utf8\"));\n } catch (error) {\n throw new Error(\n `Cannot read the env file ${envFile}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n}\n\nexport function formatHostIssues(\n file: string,\n issues: readonly HostIssue[],\n deferred: number,\n): string {\n if (issues.length === 0) {\n const note =\n deferred > 0\n ? `\\n ${deferred} output token(s) checked declared-only`\n : \"\";\n return `${file}: ok${note}`;\n }\n const byFile = new Map<string, HostIssue[]>();\n for (const issue of issues) {\n byFile.set(issue.file, [...(byFile.get(issue.file) ?? []), issue]);\n }\n const blocks = [...byFile].map(([at, found]) => {\n const lines = found.flatMap((issue) => {\n const where = issue.path ? `${issue.path}: ` : \"\";\n const line = ` ${issue.stage} ${where}${issue.message.replaceAll(\"\\n\", \"\\n \")}`;\n return issue.hint ? [line, ` hint: ${issue.hint}`] : [line];\n });\n return [at, ...lines].join(\"\\n\");\n });\n return blocks.join(\"\\n\\n\");\n}\n\n/** `ph host check <host>`: every issue `ph run` would hit; exits 1 on any. */\nexport async function runHostCheck(\n args: HostCheckArgs,\n): Promise<{ output: string; exitCode: number }> {\n const projectRoot = args.projectRoot ?? process.cwd();\n const env = await checkEnv(projectRoot, args.envFile);\n const { issues, deferred } = await checkHost(args.host, {\n projectRoot,\n env,\n ...(args.verb !== undefined ? { verb: args.verb } : {}),\n });\n return {\n output: formatHostIssues(\n `hosts/${args.host}/host.js`,\n issues,\n deferred.length,\n ),\n exitCode: issues.length > 0 ? 1 : 0,\n };\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAmBA,eAAe,SACb,aACA,SAC6C;CAC7C,IAAI,YAAY,KAAA,GAAW;EACzB,eA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AAE,QAAQ,aAAa,MAAM,UAAU,KAAK,MAAM;EACtD;EACA;EACA,GAAI,KAAK,SAAS,KAAA,IAAY,EAAE,MAAM,KAAK,KAAK,IAAI,CAAC;CACvD,CAAC;CACD,OAAO;EACL,QAAQ,iBACN,SAAS,KAAK,KAAK,WACnB,QACA,SAAS,MACX;EACA,UAAU,OAAO,SAAS,IAAI,IAAI;CACpC;AACF","debug_id":"8c7ada8c-f4b9-5527-bc5f-8a7110589167"}
1
+ {"version":3,"file":"check-o9kpHrG_.mjs","sources":["../src/services/host/check.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { checkHost, type HostIssue } from \"@powerhousedao/host-core\";\nimport { CALLER_CWD_ENV } from \"@powerhousedao/shared/clis/command-names\";\nimport {\n envNamesBeforeProjectEnv,\n loadProjectEnv,\n} from \"@powerhousedao/shared/clis/project-env\";\nimport dotenv from \"dotenv\";\nimport { rememberShellNames } from \"../../runners/member-config.js\";\n\nexport interface HostCheckArgs {\n host: string;\n envFile?: string;\n verb?: string;\n projectRoot?: string;\n}\n\n/** Without `envFile`: what `ph run` sees (project .env under process env). */\nasync function checkEnv(\n projectRoot: string,\n envFile: string | undefined,\n): Promise<Record<string, string | undefined>> {\n if (envFile === undefined) {\n loadProjectEnv(projectRoot);\n // A snapshot: a .env a runner's checkBoot loads later never reaches it.\n const env = { ...process.env };\n // The switchboard's checkBoot puts the .env's values under the host file.\n rememberShellNames(env, envNamesBeforeProjectEnv() ?? Object.keys(env));\n return env;\n }\n const from = process.env[CALLER_CWD_ENV] ?? process.cwd();\n try {\n return dotenv.parse(await readFile(path.resolve(from, envFile), \"utf8\"));\n } catch (error) {\n throw new Error(\n `Cannot read the env file ${envFile}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n}\n\nexport function formatHostIssues(\n file: string,\n issues: readonly HostIssue[],\n deferred: number,\n): string {\n if (issues.length === 0) {\n const note =\n deferred > 0\n ? `\\n ${deferred} output token(s) checked declared-only`\n : \"\";\n return `${file}: ok${note}`;\n }\n const byFile = new Map<string, HostIssue[]>();\n for (const issue of issues) {\n byFile.set(issue.file, [...(byFile.get(issue.file) ?? []), issue]);\n }\n const blocks = [...byFile].map(([at, found]) => {\n const lines = found.flatMap((issue) => {\n const where = issue.path ? `${issue.path}: ` : \"\";\n const line = ` ${issue.stage} ${where}${issue.message.replaceAll(\"\\n\", \"\\n \")}`;\n return issue.hint ? [line, ` hint: ${issue.hint}`] : [line];\n });\n return [at, ...lines].join(\"\\n\");\n });\n return blocks.join(\"\\n\\n\");\n}\n\n/** `ph host check <host>`: every issue `ph run` would hit; exits 1 on any. */\nexport async function runHostCheck(\n args: HostCheckArgs,\n): Promise<{ output: string; exitCode: number }> {\n const projectRoot = args.projectRoot ?? process.cwd();\n const env = await checkEnv(projectRoot, args.envFile);\n const { issues, deferred } = await checkHost(args.host, {\n projectRoot,\n env,\n ...(args.verb !== undefined ? { verb: args.verb } : {}),\n });\n return {\n output: formatHostIssues(\n `hosts/${args.host}/host.js`,\n issues,\n deferred.length,\n ),\n exitCode: issues.length > 0 ? 1 : 0,\n };\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAmBA,eAAe,SACb,aACA,SAC6C;CAC7C,IAAI,YAAY,KAAA,GAAW;EACzB,eAAe,WAAW;EAE1B,MAAM,MAAM,EAAE,GAAG,QAAQ,IAAI;EAE7B,mBAAmB,KAAK,yBAAyB,KAAK,OAAO,KAAK,GAAG,CAAC;EACtE,OAAO;CACT;CACA,MAAM,OAAO,QAAQ,IAAI,mBAAmB,QAAQ,IAAI;CACxD,IAAI;EACF,OAAO,OAAO,MAAM,MAAM,SAAS,KAAK,QAAQ,MAAM,OAAO,GAAG,MAAM,CAAC;CACzE,SAAS,OAAO;EACd,MAAM,IAAI,MACR,4BAA4B,QAAQ,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAC7F,EAAE,OAAO,MAAM,CACjB;CACF;AACF;AAEA,SAAgB,iBACd,MACA,QACA,UACQ;CACR,IAAI,OAAO,WAAW,GAKpB,OAAO,GAAG,KAAK,MAHb,WAAW,IACP,OAAO,SAAS,0CAChB;CAGR,MAAM,yBAAS,IAAI,IAAyB;CAC5C,KAAK,MAAM,SAAS,QAClB,OAAO,IAAI,MAAM,MAAM,CAAC,GAAI,OAAO,IAAI,MAAM,IAAI,KAAK,CAAC,GAAI,KAAK,CAAC;CAUnE,OARe,CAAC,GAAG,MAAM,CAAC,CAAC,KAAK,CAAC,IAAI,WAAW;EAM9C,OAAO,CAAC,IAAI,GALE,MAAM,SAAS,UAAU;GACrC,MAAM,QAAQ,MAAM,OAAO,GAAG,MAAM,KAAK,MAAM;GAC/C,MAAM,OAAO,KAAK,MAAM,MAAM,IAAI,QAAQ,MAAM,QAAQ,WAAW,MAAM,QAAQ;GACjF,OAAO,MAAM,OAAO,CAAC,MAAM,aAAa,MAAM,MAAM,IAAI,CAAC,IAAI;EAC/D,CACmB,CAAC,CAAC,CAAC,KAAK,IAAI;CACjC,CACY,CAAC,CAAC,KAAK,MAAM;AAC3B;;AAGA,eAAsB,aACpB,MAC+C;CAC/C,MAAM,cAAc,KAAK,eAAe,QAAQ,IAAI;CACpD,MAAM,MAAM,MAAM,SAAS,aAAa,KAAK,OAAO;CACpD,MAAM,EAAE,QAAQ,aAAa,MAAM,UAAU,KAAK,MAAM;EACtD;EACA;EACA,GAAI,KAAK,SAAS,KAAA,IAAY,EAAE,MAAM,KAAK,KAAK,IAAI,CAAC;CACvD,CAAC;CACD,OAAO;EACL,QAAQ,iBACN,SAAS,KAAK,KAAK,WACnB,QACA,SAAS,MACX;EACA,UAAU,OAAO,SAAS,IAAI,IAAI;CACpC;AACF","debug_id":"85160053-9251-5dc4-810b-78262a363f93"}
package/dist/cli.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  !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]="83ce31d0-0645-5039-b36b-b7427b013283")}catch(e){}}();
4
- import { t as getVersion } from "./get-version-DYZoeX3K.mjs";
5
- import { n as phCliCommands } from "./ph-cli-commands-CkN8Mx1U.mjs";
4
+ import { t as getVersion } from "./get-version-D1U-KyKb.mjs";
5
+ import { n as phCliCommands } from "./ph-cli-commands-DoB_GolD.mjs";
6
6
  import { t as isUniformRunnersEnabled } from "./feature-flags-xwqcHEWC.mjs";
7
7
  import { initCliTelemetry } from "@powerhousedao/shared/clis/telemetry";
8
8
  import { assertNodeVersion } from "@powerhousedao/shared/clis/utils";
@@ -93,7 +93,7 @@ async function main() {
93
93
  let args = process.argv.slice(2);
94
94
  if (isUniformRunnersEnabled()) {
95
95
  const { applyRunSugar } = await import("./run-sugar-DWPDmuRj.mjs");
96
- const { phCliCommands } = await import("./ph-cli-commands-DixzcrsT.mjs");
96
+ const { phCliCommands } = await import("./ph-cli-commands-BZDpcccA.mjs");
97
97
  const sugar = applyRunSugar(args, new Set(Object.keys(phCliCommands)), process.cwd());
98
98
  if (sugar.warning) console.warn(sugar.warning);
99
99
  args = sugar.args;
@@ -1,11 +1,11 @@
1
1
  //#region src/get-version.ts
2
2
 
3
- !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]="911671c9-6307-5dc4-8948-a462ce7f3d61")}catch(e){}}();
3
+ !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]="11e1c209-9dda-513b-ab72-48b9a2a4369f")}catch(e){}}();
4
4
  function getVersion() {
5
- return "6.2.3-dev.85";
5
+ return "6.2.3-dev.86";
6
6
  }
7
7
  //#endregion
8
8
  export { getVersion as t };
9
9
 
10
- //# sourceMappingURL=get-version-DYZoeX3K.mjs.map
11
- //# debugId=911671c9-6307-5dc4-8948-a462ce7f3d61
10
+ //# sourceMappingURL=get-version-D1U-KyKb.mjs.map
11
+ //# debugId=11e1c209-9dda-513b-ab72-48b9a2a4369f
@@ -1 +1 @@
1
- {"version":3,"file":"get-version-DYZoeX3K.mjs","sources":["../src/get-version.ts"],"sourcesContent":["declare const CLI_VERSION: string | undefined;\ndeclare const CLI_GIT_SHA: string | undefined;\n\nexport function getVersion() {\n if (typeof CLI_VERSION !== \"undefined\") return CLI_VERSION;\n return (\n process.env.WORKSPACE_VERSION ||\n process.env.npm_package_version ||\n \"unknown\"\n );\n}\n\nexport function getGitHash() {\n if (typeof CLI_GIT_SHA !== \"undefined\") return CLI_GIT_SHA;\n return process.env.WORKSPACE_GIT_SHA || \"unknown\";\n}\n"],"names":[],"mappings":";;;AAGA,SAAgB,aAAa;CACa,OAAA;AAM1C","debug_id":"911671c9-6307-5dc4-8948-a462ce7f3d61"}
1
+ {"version":3,"file":"get-version-D1U-KyKb.mjs","sources":["../src/get-version.ts"],"sourcesContent":["declare const CLI_VERSION: string | undefined;\ndeclare const CLI_GIT_SHA: string | undefined;\n\nexport function getVersion() {\n if (typeof CLI_VERSION !== \"undefined\") return CLI_VERSION;\n return (\n process.env.WORKSPACE_VERSION ||\n process.env.npm_package_version ||\n \"unknown\"\n );\n}\n\nexport function getGitHash() {\n if (typeof CLI_GIT_SHA !== \"undefined\") return CLI_GIT_SHA;\n return process.env.WORKSPACE_GIT_SHA || \"unknown\";\n}\n"],"names":[],"mappings":";;;AAGA,SAAgB,aAAa;CACa,OAAA;AAM1C","debug_id":"11e1c209-9dda-513b-ab72-48b9a2a4369f"}
@@ -0,0 +1,201 @@
1
+
2
+ !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]="872a0a4c-a394-510e-9f86-0be9f6fa07cd")}catch(e){}}();
3
+ import { DEFAULT_SWITCHBOARD_PORT } from "@powerhousedao/shared/clis/constants";
4
+ import { getConfig } from "@powerhousedao/shared/clis";
5
+ import { KEYFRAME_ADMIN_OPERATIONS } from "@powerhousedao/reactor";
6
+ //#region src/services/keyframes.ts
7
+ const POLL_INTERVAL_MS = 2e3;
8
+ /** The endpoint inspection-admin is mounted at, beside `/graphql`. */
9
+ function keyframesEndpoint(url) {
10
+ const trimmed = url.replace(/\/+$/, "");
11
+ return trimmed.endsWith("/inspection-admin") ? trimmed : `${trimmed}/inspection-admin`;
12
+ }
13
+ function formatBytes(bytes) {
14
+ if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(2)} GB`;
15
+ if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
16
+ if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
17
+ return `${bytes} B`;
18
+ }
19
+ /** The result of a run as lines of text. */
20
+ function runReport(run) {
21
+ const lines = [
22
+ `${run.dryRun ? "Preview" : "Clean-up"}: ${run.state}, ${run.documentsSeen} of ${run.documentsTotal} documents`,
23
+ `Keyframes: ${run.totals.rows} (${formatBytes(run.totals.bytes)}) in ${run.totals.streams} streams`,
24
+ `${run.dryRun ? "Would remove" : "To remove"}: ${run.totals.removableRows} (${formatBytes(run.totals.removableBytes)})`
25
+ ];
26
+ if (!run.dryRun) lines.push(`Removed: ${run.totals.removedRows} (${formatBytes(run.totals.removedBytes)})`);
27
+ if (run.error !== null) lines.push(`Error: ${run.error}`);
28
+ if (run.reasons.length > 0) {
29
+ lines.push("", "By reason:");
30
+ for (const reason of run.reasons) lines.push(` ${reason.reason}: ${reason.rows} (${formatBytes(reason.bytes)})`);
31
+ }
32
+ if (run.types.length > 0) {
33
+ lines.push("", "By document type:");
34
+ for (const type of run.types) lines.push(` ${type.documentType} (interval ${type.interval}, keep ${type.keep ?? "all"}): ${type.rows} keyframes, ${formatBytes(type.bytes)}; remove ${type.removableRows}, ${formatBytes(type.removableBytes)}`);
35
+ }
36
+ if (run.topStreams.length > 0) {
37
+ lines.push("", "Largest streams:");
38
+ for (const stream of run.topStreams) lines.push(` ${stream.documentId} ${stream.scope}/${stream.branch} (${stream.documentType}, ${stream.reason}): remove ${stream.removableRows} of ${stream.rows}, ${formatBytes(stream.removableBytes)}`);
39
+ }
40
+ return lines;
41
+ }
42
+ function reclaimReport(reclaim) {
43
+ const lines = [`Reclaim: ${reclaim.state}`, reclaim.message];
44
+ if (reclaim.tableBytesBefore !== null) {
45
+ const after = reclaim.tableBytesAfter === null ? "" : ` to ${formatBytes(reclaim.tableBytesAfter)}`;
46
+ lines.push(`Keyframe table: ${formatBytes(reclaim.tableBytesBefore)}${after}`);
47
+ }
48
+ return lines;
49
+ }
50
+ function sleep(ms) {
51
+ return new Promise((resolve) => {
52
+ setTimeout(resolve, ms);
53
+ });
54
+ }
55
+ async function followRun(started, deps) {
56
+ let run = started;
57
+ let reported = -1;
58
+ while (run.state === "running") {
59
+ if (run.documentsSeen !== reported) {
60
+ reported = run.documentsSeen;
61
+ deps.output.err(`${run.documentsSeen} of ${run.documentsTotal} documents, ${run.totals.removedRows} removed${run.parked ? " (paused: catch-up priority 0)" : ""}`);
62
+ }
63
+ await sleep(deps.pollIntervalMs);
64
+ const latest = await deps.request(KEYFRAME_ADMIN_OPERATIONS.cleanup);
65
+ if (latest.inspectionKeyframeCleanup === null) throw new Error("The host lost the run: did it restart?");
66
+ run = latest.inspectionKeyframeCleanup;
67
+ }
68
+ return run;
69
+ }
70
+ async function followReclaim(started, deps) {
71
+ let reclaim = started;
72
+ while (reclaim.state === "running") {
73
+ await sleep(deps.pollIntervalMs);
74
+ const latest = await deps.request(KEYFRAME_ADMIN_OPERATIONS.reclaimStatus);
75
+ if (latest.inspectionKeyframeReclaim === null) throw new Error("The host lost the reclaim: did it restart?");
76
+ reclaim = latest.inspectionKeyframeReclaim;
77
+ }
78
+ return reclaim;
79
+ }
80
+ function printRun(run, args, deps) {
81
+ if (args.json) {
82
+ deps.output.out(JSON.stringify(run, null, 2));
83
+ return;
84
+ }
85
+ for (const line of runReport(run)) deps.output.out(line);
86
+ }
87
+ function printReclaim(reclaim, args, deps) {
88
+ if (args.json) {
89
+ deps.output.out(JSON.stringify(reclaim, null, 2));
90
+ return;
91
+ }
92
+ for (const line of reclaimReport(reclaim)) deps.output.out(line);
93
+ }
94
+ async function startAndFollow(dryRun, args, deps) {
95
+ const run = await followRun((await deps.request(KEYFRAME_ADMIN_OPERATIONS.startCleanup, { dryRun })).inspectionStartKeyframeCleanup, deps);
96
+ printRun(run, args, deps);
97
+ return run.state === "done" ? 0 : 1;
98
+ }
99
+ /** The action against a host, by way of `deps.request`. Answers the exit code. */
100
+ async function executeKeyframesAction(args, deps) {
101
+ switch (args.action) {
102
+ case "preview": return startAndFollow(true, args, deps);
103
+ case "clean":
104
+ if (!args.yes) {
105
+ deps.output.err("clean deletes keyframes. Run `ph keyframes preview` first, then add --yes.");
106
+ return 1;
107
+ }
108
+ return startAndFollow(false, args, deps);
109
+ case "status": {
110
+ const { inspectionKeyframeCleanup: run } = await deps.request(KEYFRAME_ADMIN_OPERATIONS.cleanup);
111
+ const { inspectionKeyframeReclaim: reclaim } = await deps.request(KEYFRAME_ADMIN_OPERATIONS.reclaimStatus);
112
+ if (args.json) {
113
+ deps.output.out(JSON.stringify({
114
+ run,
115
+ reclaim
116
+ }, null, 2));
117
+ return 0;
118
+ }
119
+ if (run === null) deps.output.out("No clean-up has run since the host started.");
120
+ else printRun(run, args, deps);
121
+ if (reclaim !== null) printReclaim(reclaim, args, deps);
122
+ return 0;
123
+ }
124
+ case "cancel":
125
+ await deps.request(KEYFRAME_ADMIN_OPERATIONS.cancelCleanup);
126
+ deps.output.out("The running clean-up stops after its current statement.");
127
+ return 0;
128
+ case "reclaim": {
129
+ if (!args.yes) {
130
+ deps.output.err("reclaim rewrites the Keyframe table; the store answers nothing while it does. Add --yes.");
131
+ return 1;
132
+ }
133
+ const reclaim = await followReclaim((await deps.request(KEYFRAME_ADMIN_OPERATIONS.reclaim)).inspectionReclaimKeyframeSpace, deps);
134
+ printReclaim(reclaim, args, deps);
135
+ return reclaim.state === "done" || reclaim.state === "unsupported" ? 0 : 1;
136
+ }
137
+ }
138
+ }
139
+ /** A request against `endpoint` with `bearer`, refusing a GraphQL error. */
140
+ function keyframesRequest(endpoint, bearer, fetchImpl = fetch) {
141
+ return async (query, variables = {}) => {
142
+ const response = await fetchImpl(endpoint, {
143
+ method: "POST",
144
+ headers: {
145
+ "content-type": "application/json",
146
+ ...bearer ? { authorization: `Bearer ${bearer}` } : {}
147
+ },
148
+ body: JSON.stringify({
149
+ query,
150
+ variables
151
+ })
152
+ });
153
+ const text = await response.text();
154
+ let body;
155
+ try {
156
+ body = JSON.parse(text);
157
+ } catch {
158
+ throw new Error(`${endpoint} answered ${response.status} without GraphQL. Is inspection-admin served (INSPECTION_ADMIN_ENABLED=true)?`);
159
+ }
160
+ const failure = body.errors?.[0];
161
+ if (failure) {
162
+ const hint = failure.extensions?.code === "FORBIDDEN" ? " The caller must be one of the host's auth admins." : "";
163
+ throw new Error(`${failure.message}${hint}`);
164
+ }
165
+ if (!body.data) throw new Error(`${endpoint} answered ${response.status} with no data`);
166
+ return body.data;
167
+ };
168
+ }
169
+ function defaultGraphqlUrl() {
170
+ return `http://localhost:${getConfig().reactor?.port ?? DEFAULT_SWITCHBOARD_PORT}/graphql`;
171
+ }
172
+ async function bearerToken(given) {
173
+ const known = given ?? process.env.PH_ACCESS_TOKEN;
174
+ if (known) return known;
175
+ const { generateAccessToken } = await import("@renown/sdk/node");
176
+ const { getRenown } = await import("./auth-CNhbN5UM.mjs");
177
+ const { token } = await generateAccessToken(await getRenown(), { expiresIn: 3600 });
178
+ return token;
179
+ }
180
+ /** Runs `ph keyframes <action>`; answers the process exit code. */
181
+ async function runKeyframesCommand(args) {
182
+ const output = {
183
+ out: (line) => console.log(line),
184
+ err: (line) => console.error(line)
185
+ };
186
+ try {
187
+ return await executeKeyframesAction(args, {
188
+ request: keyframesRequest(keyframesEndpoint(args.url ?? defaultGraphqlUrl()), await bearerToken(args.token)),
189
+ output,
190
+ pollIntervalMs: POLL_INTERVAL_MS
191
+ });
192
+ } catch (error) {
193
+ output.err(error instanceof Error ? error.message : String(error));
194
+ return 1;
195
+ }
196
+ }
197
+ //#endregion
198
+ export { runKeyframesCommand };
199
+
200
+ //# sourceMappingURL=keyframes-bFo9iDhT.mjs.map
201
+ //# debugId=872a0a4c-a394-510e-9f86-0be9f6fa07cd
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keyframes-bFo9iDhT.mjs","sources":["../src/services/keyframes.ts"],"sourcesContent":["import {\n KEYFRAME_ADMIN_OPERATIONS,\n type KeyframeCleanupRun,\n type KeyframeReclaim,\n} from \"@powerhousedao/reactor\";\nimport { getConfig } from \"@powerhousedao/shared/clis\";\nimport { DEFAULT_SWITCHBOARD_PORT } from \"@powerhousedao/shared/clis/constants\";\n\nexport type KeyframesAction =\n | \"preview\"\n | \"clean\"\n | \"status\"\n | \"cancel\"\n | \"reclaim\";\n\nexport type KeyframesCommandArgs = {\n action: KeyframesAction;\n url?: string;\n token?: string;\n yes?: boolean;\n json?: boolean;\n};\n\ntype GraphqlResponse<T> = {\n data?: T | null;\n errors?: { message: string; extensions?: { code?: string } }[];\n};\n\n/** One call to the host's `inspection-admin` subgraph. */\nexport type KeyframesRequest = <T>(\n query: string,\n variables?: Record<string, unknown>,\n) => Promise<T>;\n\nexport type KeyframesOutput = {\n out: (line: string) => void;\n err: (line: string) => void;\n};\n\nexport type KeyframesDeps = {\n request: KeyframesRequest;\n output: KeyframesOutput;\n pollIntervalMs: number;\n};\n\nconst POLL_INTERVAL_MS = 2_000;\n\n/** The endpoint inspection-admin is mounted at, beside `/graphql`. */\nexport function keyframesEndpoint(url: string): string {\n const trimmed = url.replace(/\\/+$/, \"\");\n return trimmed.endsWith(\"/inspection-admin\")\n ? trimmed\n : `${trimmed}/inspection-admin`;\n}\n\nexport function formatBytes(bytes: number): string {\n if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(2)} GB`;\n if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)} MB`;\n if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${bytes} B`;\n}\n\n/** The result of a run as lines of text. */\nexport function runReport(run: KeyframeCleanupRun): string[] {\n const lines = [\n `${run.dryRun ? \"Preview\" : \"Clean-up\"}: ${run.state}, ${run.documentsSeen} of ${run.documentsTotal} documents`,\n `Keyframes: ${run.totals.rows} (${formatBytes(run.totals.bytes)}) in ${run.totals.streams} streams`,\n `${run.dryRun ? \"Would remove\" : \"To remove\"}: ${run.totals.removableRows} (${formatBytes(run.totals.removableBytes)})`,\n ];\n if (!run.dryRun) {\n lines.push(\n `Removed: ${run.totals.removedRows} (${formatBytes(run.totals.removedBytes)})`,\n );\n }\n if (run.error !== null) {\n lines.push(`Error: ${run.error}`);\n }\n if (run.reasons.length > 0) {\n lines.push(\"\", \"By reason:\");\n for (const reason of run.reasons) {\n lines.push(\n ` ${reason.reason}: ${reason.rows} (${formatBytes(reason.bytes)})`,\n );\n }\n }\n if (run.types.length > 0) {\n lines.push(\"\", \"By document type:\");\n for (const type of run.types) {\n lines.push(\n ` ${type.documentType} (interval ${type.interval}, keep ${type.keep ?? \"all\"}): ${type.rows} keyframes, ${formatBytes(type.bytes)}; remove ${type.removableRows}, ${formatBytes(type.removableBytes)}`,\n );\n }\n }\n if (run.topStreams.length > 0) {\n lines.push(\"\", \"Largest streams:\");\n for (const stream of run.topStreams) {\n lines.push(\n ` ${stream.documentId} ${stream.scope}/${stream.branch} (${stream.documentType}, ${stream.reason}): remove ${stream.removableRows} of ${stream.rows}, ${formatBytes(stream.removableBytes)}`,\n );\n }\n }\n return lines;\n}\n\nfunction reclaimReport(reclaim: KeyframeReclaim): string[] {\n const lines = [`Reclaim: ${reclaim.state}`, reclaim.message];\n if (reclaim.tableBytesBefore !== null) {\n const after =\n reclaim.tableBytesAfter === null\n ? \"\"\n : ` to ${formatBytes(reclaim.tableBytesAfter)}`;\n lines.push(\n `Keyframe table: ${formatBytes(reclaim.tableBytesBefore)}${after}`,\n );\n }\n return lines;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nasync function followRun(\n started: KeyframeCleanupRun,\n deps: KeyframesDeps,\n): Promise<KeyframeCleanupRun> {\n let run = started;\n let reported = -1;\n while (run.state === \"running\") {\n if (run.documentsSeen !== reported) {\n reported = run.documentsSeen;\n deps.output.err(\n `${run.documentsSeen} of ${run.documentsTotal} documents, ${run.totals.removedRows} removed${run.parked ? \" (paused: catch-up priority 0)\" : \"\"}`,\n );\n }\n await sleep(deps.pollIntervalMs);\n const latest = await deps.request<{\n inspectionKeyframeCleanup: KeyframeCleanupRun | null;\n }>(KEYFRAME_ADMIN_OPERATIONS.cleanup);\n if (latest.inspectionKeyframeCleanup === null) {\n throw new Error(\"The host lost the run: did it restart?\");\n }\n run = latest.inspectionKeyframeCleanup;\n }\n return run;\n}\n\nasync function followReclaim(\n started: KeyframeReclaim,\n deps: KeyframesDeps,\n): Promise<KeyframeReclaim> {\n let reclaim = started;\n while (reclaim.state === \"running\") {\n await sleep(deps.pollIntervalMs);\n const latest = await deps.request<{\n inspectionKeyframeReclaim: KeyframeReclaim | null;\n }>(KEYFRAME_ADMIN_OPERATIONS.reclaimStatus);\n if (latest.inspectionKeyframeReclaim === null) {\n throw new Error(\"The host lost the reclaim: did it restart?\");\n }\n reclaim = latest.inspectionKeyframeReclaim;\n }\n return reclaim;\n}\n\nfunction printRun(\n run: KeyframeCleanupRun,\n args: KeyframesCommandArgs,\n deps: KeyframesDeps,\n): void {\n if (args.json) {\n deps.output.out(JSON.stringify(run, null, 2));\n return;\n }\n for (const line of runReport(run)) deps.output.out(line);\n}\n\nfunction printReclaim(\n reclaim: KeyframeReclaim,\n args: KeyframesCommandArgs,\n deps: KeyframesDeps,\n): void {\n if (args.json) {\n deps.output.out(JSON.stringify(reclaim, null, 2));\n return;\n }\n for (const line of reclaimReport(reclaim)) deps.output.out(line);\n}\n\nasync function startAndFollow(\n dryRun: boolean,\n args: KeyframesCommandArgs,\n deps: KeyframesDeps,\n): Promise<number> {\n const started = await deps.request<{\n inspectionStartKeyframeCleanup: KeyframeCleanupRun;\n }>(KEYFRAME_ADMIN_OPERATIONS.startCleanup, { dryRun });\n const run = await followRun(started.inspectionStartKeyframeCleanup, deps);\n printRun(run, args, deps);\n return run.state === \"done\" ? 0 : 1;\n}\n\n/** The action against a host, by way of `deps.request`. Answers the exit code. */\nexport async function executeKeyframesAction(\n args: KeyframesCommandArgs,\n deps: KeyframesDeps,\n): Promise<number> {\n switch (args.action) {\n case \"preview\":\n return startAndFollow(true, args, deps);\n case \"clean\":\n if (!args.yes) {\n deps.output.err(\n \"clean deletes keyframes. Run `ph keyframes preview` first, then add --yes.\",\n );\n return 1;\n }\n return startAndFollow(false, args, deps);\n case \"status\": {\n const { inspectionKeyframeCleanup: run } = await deps.request<{\n inspectionKeyframeCleanup: KeyframeCleanupRun | null;\n }>(KEYFRAME_ADMIN_OPERATIONS.cleanup);\n const { inspectionKeyframeReclaim: reclaim } = await deps.request<{\n inspectionKeyframeReclaim: KeyframeReclaim | null;\n }>(KEYFRAME_ADMIN_OPERATIONS.reclaimStatus);\n if (args.json) {\n deps.output.out(JSON.stringify({ run, reclaim }, null, 2));\n return 0;\n }\n if (run === null) {\n deps.output.out(\"No clean-up has run since the host started.\");\n } else {\n printRun(run, args, deps);\n }\n if (reclaim !== null) {\n printReclaim(reclaim, args, deps);\n }\n return 0;\n }\n case \"cancel\":\n await deps.request(KEYFRAME_ADMIN_OPERATIONS.cancelCleanup);\n deps.output.out(\n \"The running clean-up stops after its current statement.\",\n );\n return 0;\n case \"reclaim\": {\n if (!args.yes) {\n deps.output.err(\n \"reclaim rewrites the Keyframe table; the store answers nothing while it does. Add --yes.\",\n );\n return 1;\n }\n const started = await deps.request<{\n inspectionReclaimKeyframeSpace: KeyframeReclaim;\n }>(KEYFRAME_ADMIN_OPERATIONS.reclaim);\n const reclaim = await followReclaim(\n started.inspectionReclaimKeyframeSpace,\n deps,\n );\n printReclaim(reclaim, args, deps);\n return reclaim.state === \"done\" || reclaim.state === \"unsupported\"\n ? 0\n : 1;\n }\n }\n}\n\n/** A request against `endpoint` with `bearer`, refusing a GraphQL error. */\nexport function keyframesRequest(\n endpoint: string,\n bearer: string | undefined,\n fetchImpl: typeof fetch = fetch,\n): KeyframesRequest {\n return async <T>(query: string, variables: Record<string, unknown> = {}) => {\n const response = await fetchImpl(endpoint, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(bearer ? { authorization: `Bearer ${bearer}` } : {}),\n },\n body: JSON.stringify({ query, variables }),\n });\n const text = await response.text();\n let body: GraphqlResponse<T>;\n try {\n body = JSON.parse(text) as GraphqlResponse<T>;\n } catch {\n throw new Error(\n `${endpoint} answered ${response.status} without GraphQL. Is inspection-admin served (INSPECTION_ADMIN_ENABLED=true)?`,\n );\n }\n const failure = body.errors?.[0];\n if (failure) {\n const hint =\n failure.extensions?.code === \"FORBIDDEN\"\n ? \" The caller must be one of the host's auth admins.\"\n : \"\";\n throw new Error(`${failure.message}${hint}`);\n }\n if (!body.data) {\n throw new Error(`${endpoint} answered ${response.status} with no data`);\n }\n return body.data;\n };\n}\n\nfunction defaultGraphqlUrl(): string {\n const port = getConfig().reactor?.port ?? DEFAULT_SWITCHBOARD_PORT;\n return `http://localhost:${port}/graphql`;\n}\n\nasync function bearerToken(given: string | undefined): Promise<string> {\n const known = given ?? process.env.PH_ACCESS_TOKEN;\n if (known) return known;\n const { generateAccessToken } = await import(\"@renown/sdk/node\");\n const { getRenown } = await import(\"./auth.js\");\n const { token } = await generateAccessToken(await getRenown(), {\n expiresIn: 3600,\n });\n return token;\n}\n\n/** Runs `ph keyframes <action>`; answers the process exit code. */\nexport async function runKeyframesCommand(\n args: KeyframesCommandArgs,\n): Promise<number> {\n const output: KeyframesOutput = {\n out: (line) => console.log(line),\n err: (line) => console.error(line),\n };\n try {\n const request = keyframesRequest(\n keyframesEndpoint(args.url ?? defaultGraphqlUrl()),\n await bearerToken(args.token),\n );\n return await executeKeyframesAction(args, {\n request,\n output,\n pollIntervalMs: POLL_INTERVAL_MS,\n });\n } catch (error) {\n output.err(error instanceof Error ? error.message : String(error));\n return 1;\n }\n}\n"],"names":[],"mappings":";;;;;;AA6CA,MAAM,mBAAmB;;AAGzB,SAAgB,kBAAkB,KAAqB;CACrD,MAAM,UAAU,IAAI,QAAQ,QAAQ,EAAE;CACtC,OAAO,QAAQ,SAAS,mBAAmB,IACvC,UACA,GAAG,QAAQ;AACjB;AAEA,SAAgB,YAAY,OAAuB;CACjD,IAAI,SAAS,QAAQ,GAAG,OAAO,IAAI,QAAQ,QAAQ,EAAA,CAAG,QAAQ,CAAC,EAAE;CACjE,IAAI,SAAS,QAAQ,GAAG,OAAO,IAAI,QAAQ,QAAQ,EAAA,CAAG,QAAQ,CAAC,EAAE;CACjE,IAAI,SAAS,MAAM,OAAO,IAAI,QAAQ,KAAA,CAAM,QAAQ,CAAC,EAAE;CACvD,OAAO,GAAG,MAAM;AAClB;;AAGA,SAAgB,UAAU,KAAmC;CAC3D,MAAM,QAAQ;EACZ,GAAG,IAAI,SAAS,YAAY,WAAW,IAAI,IAAI,MAAM,IAAI,IAAI,cAAc,MAAM,IAAI,eAAe;EACpG,cAAc,IAAI,OAAO,KAAK,IAAI,YAAY,IAAI,OAAO,KAAK,EAAE,OAAO,IAAI,OAAO,QAAQ;EAC1F,GAAG,IAAI,SAAS,iBAAiB,YAAY,IAAI,IAAI,OAAO,cAAc,IAAI,YAAY,IAAI,OAAO,cAAc,EAAE;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Y,KAAK,KAAK,CAGtB;GACN;GACA,gBAAgB;EAClB,CAAC;CACH,SAAS,OAAO;EACd,OAAO,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;EACjE,OAAO;CACT;AACF","debug_id":"872a0a4c-a394-510e-9f86-0be9f6fa07cd"}
@@ -1,6 +1,6 @@
1
1
 
2
- !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]="0af8aa59-ede1-5687-a804-d6a7e425a08b")}catch(e){}}();
3
- import { t as getVersion } from "./get-version-DYZoeX3K.mjs";
2
+ !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]="3bb6193f-0a25-5eb5-8077-3f3b52ec8b22")}catch(e){}}();
3
+ import { t as getVersion } from "./get-version-D1U-KyKb.mjs";
4
4
  import { i as restartVetra, l as readVetraRuntime, n as currentPhCliVetraCommand, r as ensureVetra, t as VetraStartError } from "./vetra-launch-DQDZxGTV.mjs";
5
5
  import { resolveSwitchboardPortDefault } from "@powerhousedao/shared/clis/args";
6
6
  import fs from "node:fs";
@@ -258,5 +258,5 @@ async function startMcpLauncher(options) {
258
258
  //#endregion
259
259
  export { startMcpLauncher };
260
260
 
261
- //# sourceMappingURL=mcp-DzxVWwmn.mjs.map
262
- //# debugId=0af8aa59-ede1-5687-a804-d6a7e425a08b
261
+ //# sourceMappingURL=mcp-tMRVrU0l.mjs.map
262
+ //# debugId=3bb6193f-0a25-5eb5-8077-3f3b52ec8b22
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-DzxVWwmn.mjs","sources":["../src/services/mcp.ts"],"sourcesContent":["import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPError,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n CallToolRequestSchema,\n CallToolResultSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ListToolsRequestSchema,\n McpError,\n ReadResourceRequestSchema,\n type CallToolRequest,\n type CallToolResult,\n type Tool,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { createServer } from \"@powerhousedao/reactor-mcp\";\nimport { resolveSwitchboardPortDefault } from \"@powerhousedao/shared/clis/args\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getVersion } from \"../get-version.js\";\nimport {\n currentPhCliVetraCommand,\n ensureVetra,\n restartVetra,\n VetraStartError,\n type EnsureVetraOptions,\n type VetraCommand,\n} from \"../utils/vetra-launch.js\";\nimport {\n readVetraRuntime,\n type VetraRuntimeRecord,\n} from \"../utils/vetra-runtime.js\";\n\nconst CALL_TIMEOUT_MS = 10 * 60_000;\nconst CONFIG_FILE = \"powerhouse.config.json\";\n\nexport type McpLauncherOptions = {\n projectDir?: string;\n startTimeoutSeconds: number;\n /** Test seam: what starts Vetra; defaults to this ph-cli's `vetra`. */\n vetraCommand?: VetraCommand;\n};\n\n/** The nearest directory at or above `start` holding powerhouse.config.json. */\nexport function findProjectDir(start: string): string | undefined {\n let dir = path.resolve(start);\n for (;;) {\n if (fs.existsSync(path.join(dir, CONFIG_FILE))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\n// The tool list never touches the reactor, so a client that throws on use is enough.\nconst reactorlessClient = new Proxy({} as IReactorClient, {\n get(_target, property) {\n if (property === \"then\") return undefined;\n return () => {\n throw new Error(\"reactor-mcp's local tool list has no reactor\");\n };\n },\n});\n\n/** reactor-mcp's own server, in-process, for the tool list and resources. */\nasync function connectLocalReactorMcp(): Promise<Client> {\n const server = await createServer({ client: reactorlessClient });\n const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();\n await server.connect(serverSide);\n const client = new Client({ name: \"ph-mcp\", version: getVersion() });\n await client.connect(clientSide);\n return client;\n}\n\nfunction toolError(message: string): CallToolResult {\n return { isError: true, content: [{ type: \"text\", text: message }] };\n}\n\n/** The call never reached a live session: Vetra is down, or restarted since. */\nfunction isStaleConnection(error: unknown): boolean {\n if (error instanceof StreamableHTTPError) {\n return error.code === 404 || error.code === 400;\n }\n for (let e = error; e instanceof Error; e = e.cause) {\n if ((e as NodeJS.ErrnoException).code === \"ECONNREFUSED\") return true;\n }\n return false;\n}\n\nexport const RESTART_VETRA_TOOL = \"restartVetra\";\n\nconst restartVetraTool: Tool = {\n name: RESTART_VETRA_TOOL,\n description:\n \"Restart this project's Vetra (its Switchboard and Studio) and wait until it is ready. \" +\n \"Use it after a change Vetra reads only at startup, such as the reactor or packages settings \" +\n \"in powerhouse.config.json; Studio restarts by itself for connect.* changes. \" +\n \"Returns the new Connect, Switchboard and MCP URLs.\",\n inputSchema: { type: \"object\", properties: {} },\n outputSchema: {\n type: \"object\",\n properties: {\n pid: { type: \"number\" },\n connectUrl: { type: \"string\" },\n switchboardUrl: { type: \"string\" },\n mcpUrl: { type: \"string\" },\n },\n required: [\"pid\", \"mcpUrl\"],\n },\n};\n\nfunction vetraUrls(record: VetraRuntimeRecord) {\n return {\n pid: record.pid,\n ...(record.connectUrl ? { connectUrl: record.connectUrl } : {}),\n switchboardUrl:\n record.switchboardUrl ??\n `http://localhost:${record.switchboardPort}/graphql`,\n mcpUrl: record.mcpUrl || `http://localhost:${record.switchboardPort}/mcp`,\n };\n}\n\nfunction projectName(projectDir: string): string | undefined {\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(projectDir, \"package.json\"), \"utf8\"),\n ) as { name?: string };\n return pkg.name;\n } catch {\n return undefined;\n }\n}\n\n/** Connects to the project's Vetra `/mcp`, starting Vetra when it is down. */\ntype Progress = (message: string) => void;\n\nclass Upstream {\n #client: Promise<Client> | undefined;\n /** The Vetra the client talks to; another pid in the record means it restarted. */\n #pid: number | undefined;\n /** The calls waiting on the connection, told how Vetra's start goes. */\n #waiting = new Set<Progress>();\n\n constructor(\n private readonly projectDir: string | undefined,\n private readonly options: McpLauncherOptions,\n ) {}\n\n get(onProgress?: Progress): Promise<Client> {\n if (this.#client && this.#pid !== undefined && this.projectDir) {\n const pid = readVetraRuntime(this.projectDir)?.pid;\n if (pid !== this.#pid) this.reset();\n }\n this.#client ??= this.#connect(ensureVetra).catch((error: unknown) => {\n this.#client = undefined;\n throw error;\n });\n return this.#waitWith(this.#client, onProgress);\n }\n\n async #waitWith<T>(task: Promise<T>, onProgress?: Progress): Promise<T> {\n if (onProgress) this.#waiting.add(onProgress);\n try {\n return await task;\n } finally {\n if (onProgress) this.#waiting.delete(onProgress);\n }\n }\n\n #report = (message: string) => {\n for (const progress of this.#waiting) progress(message);\n };\n\n reset(): void {\n const stale = this.#client;\n this.#client = undefined;\n this.#pid = undefined;\n void stale?.then((client) => client.close()).catch(() => {});\n }\n\n /** Restarts Vetra and connects to the new one; resolves to its record. */\n async restart(onProgress?: Progress): Promise<VetraRuntimeRecord> {\n this.reset();\n let record: VetraRuntimeRecord | undefined;\n const connected = this.#connect(async (options) => {\n record = await restartVetra(options);\n return record;\n });\n this.#client = connected.catch((error: unknown) => {\n this.#client = undefined;\n throw error;\n });\n await this.#waitWith(this.#client, onProgress);\n return record!;\n }\n\n async #connect(\n start: (options: EnsureVetraOptions) => Promise<VetraRuntimeRecord>,\n ): Promise<Client> {\n const { projectDir } = this;\n if (!projectDir) {\n throw new VetraStartError(\n `No Powerhouse project (${CONFIG_FILE}) at or above ${process.cwd()}. Run \\`ph mcp\\` inside the project, or pass --project-dir.`,\n );\n }\n const name = projectName(projectDir);\n if (!name) {\n throw new VetraStartError(`${projectDir} has no package.json name.`);\n }\n console.error(`[ph mcp] connecting to Vetra for ${name}...`);\n const record = await start({\n projectDir,\n projectName: name,\n switchboardPort: resolveSwitchboardPortDefault(),\n command: this.options.vetraCommand ?? currentPhCliVetraCommand(),\n timeoutMs: this.options.startTimeoutSeconds * 1000,\n onProgress: this.#report,\n });\n const { mcpUrl } = vetraUrls(record);\n const client = new Client({ name: \"ph-mcp\", version: getVersion() });\n await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl)));\n this.#pid = record.pid;\n console.error(`[ph mcp] forwarding tool calls to ${mcpUrl}`);\n return client;\n }\n}\n\nasync function forwardToolCall(\n upstream: Upstream,\n params: CallToolRequest[\"params\"],\n signal: AbortSignal,\n onProgress: Progress,\n): Promise<CallToolResult> {\n for (let attempt = 0; ; attempt++) {\n const client = await upstream.get(onProgress);\n try {\n return await client.request(\n { method: \"tools/call\", params },\n CallToolResultSchema,\n { signal, timeout: CALL_TIMEOUT_MS },\n );\n } catch (error) {\n // It never arrived: Vetra went away or restarted, so find or start it again.\n if (attempt > 0 || !isStaleConnection(error)) throw error;\n upstream.reset();\n }\n }\n}\n\n/** `ph mcp`: tools listed by in-process reactor-mcp, calls forwarded to Vetra (started on first call). */\nexport async function startMcpLauncher(options: McpLauncherOptions) {\n // stdout carries JSON-RPC only.\n console.log = console.error;\n console.info = console.error;\n\n const projectDir = findProjectDir(\n options.projectDir ?? process.env.PH_CALLER_CWD ?? process.cwd(),\n );\n // Port resolution and `ph vetra` both read the project from the cwd.\n if (projectDir) process.chdir(projectDir);\n\n const local = await connectLocalReactorMcp();\n const upstream = new Upstream(projectDir, options);\n const server = new Server(\n local.getServerVersion() ?? { name: \"reactor-mcp-server\", version: \"\" },\n {\n capabilities: { tools: {}, resources: {} },\n instructions: local.getInstructions(),\n },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async (request) => {\n const listed = await local.listTools(request.params);\n return { ...listed, tools: [...listed.tools, restartVetraTool] };\n });\n server.setRequestHandler(ListResourcesRequestSchema, (request) =>\n local.listResources(request.params),\n );\n server.setRequestHandler(ListResourceTemplatesRequestSchema, (request) =>\n local.listResourceTemplates(request.params),\n );\n server.setRequestHandler(ReadResourceRequestSchema, (request) =>\n local.readResource(request.params),\n );\n server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\n // How Vetra's start goes: progress notifications when the client asked, else stderr.\n const token = request.params._meta?.progressToken;\n let progress = 0;\n const onProgress: Progress = (message) => {\n if (token === undefined) {\n console.error(`[ph mcp] ${message}`);\n return;\n }\n void extra\n .sendNotification({\n method: \"notifications/progress\",\n params: { progressToken: token, progress: ++progress, message },\n })\n .catch(() => {});\n };\n try {\n if (request.params.name === RESTART_VETRA_TOOL) {\n const urls = vetraUrls(await upstream.restart(onProgress));\n return {\n content: [{ type: \"text\", text: JSON.stringify(urls) }],\n structuredContent: urls,\n };\n }\n return await forwardToolCall(\n upstream,\n request.params,\n extra.signal,\n onProgress,\n );\n } catch (error) {\n // Protocol errors from reactor-mcp reach the agent as they would over HTTP.\n if (error instanceof McpError) throw error;\n const message = error instanceof Error ? error.message : String(error);\n return toolError(\n error instanceof VetraStartError\n ? message\n : `reactor-mcp request failed: ${message}`,\n );\n }\n });\n\n const transport = new StdioServerTransport();\n transport.onclose = () => process.exit(0);\n process.stdin.once(\"end\", () => process.exit(0));\n await server.connect(transport);\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAuCA,MAAM,kBAAkB;AACxB,MAAM,cAAc;;AAUpB,SAAgB,eAAe,OAAmC;CAChE,IAAI,MAAM,KAAK,QAAQ,KAAK;CAC5B,SAAS;EACP,IAAI,GAAG,WAAW,KAAK,KAAK,KAAK,WAAW,CAAC,GAAG,OAAO;EACvD,MAAM,SAAS,KAAK,QAAQ,GAAG;EAC/B,IAAI,WAAW,KAAK,OAAO,KAAA;EAC3B,MAAM;CACR;AACF;AAGA,MAAM,oBAAoB,IAAI,MAAM,CAAC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AQ,MAAM,KAAK,UAAU,IAAI;KAAE,CAAC;KACtD,mBAAmB;IACrB;GACF;GACA,OAAO,MAAM,gBACX,UACA,QAAQ,QACR,MAAM,QACN,UACF;EACF,SAAS,OAAO;GAEd,IAAI,iBAAiB,UAAU,MAAM;GACrC,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACrE,OAAO,UACL,iBAAiB,kBACb,UACA,+BAA+B,SACrC;EACF;CACF,CAAC;CAED,MAAM,YAAY,IAAI,qBAAqB;CAC3C,UAAU,gBAAgB,QAAQ,KAAK,CAAC;CACxC,QAAQ,MAAM,KAAK,aAAa,QAAQ,KAAK,CAAC,CAAC;CAC/C,MAAM,OAAO,QAAQ,SAAS;AAChC","debug_id":"0af8aa59-ede1-5687-a804-d6a7e425a08b"}
1
+ {"version":3,"file":"mcp-tMRVrU0l.mjs","sources":["../src/services/mcp.ts"],"sourcesContent":["import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPError,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n CallToolRequestSchema,\n CallToolResultSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ListToolsRequestSchema,\n McpError,\n ReadResourceRequestSchema,\n type CallToolRequest,\n type CallToolResult,\n type Tool,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { createServer } from \"@powerhousedao/reactor-mcp\";\nimport { resolveSwitchboardPortDefault } from \"@powerhousedao/shared/clis/args\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getVersion } from \"../get-version.js\";\nimport {\n currentPhCliVetraCommand,\n ensureVetra,\n restartVetra,\n VetraStartError,\n type EnsureVetraOptions,\n type VetraCommand,\n} from \"../utils/vetra-launch.js\";\nimport {\n readVetraRuntime,\n type VetraRuntimeRecord,\n} from \"../utils/vetra-runtime.js\";\n\nconst CALL_TIMEOUT_MS = 10 * 60_000;\nconst CONFIG_FILE = \"powerhouse.config.json\";\n\nexport type McpLauncherOptions = {\n projectDir?: string;\n startTimeoutSeconds: number;\n /** Test seam: what starts Vetra; defaults to this ph-cli's `vetra`. */\n vetraCommand?: VetraCommand;\n};\n\n/** The nearest directory at or above `start` holding powerhouse.config.json. */\nexport function findProjectDir(start: string): string | undefined {\n let dir = path.resolve(start);\n for (;;) {\n if (fs.existsSync(path.join(dir, CONFIG_FILE))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\n// The tool list never touches the reactor, so a client that throws on use is enough.\nconst reactorlessClient = new Proxy({} as IReactorClient, {\n get(_target, property) {\n if (property === \"then\") return undefined;\n return () => {\n throw new Error(\"reactor-mcp's local tool list has no reactor\");\n };\n },\n});\n\n/** reactor-mcp's own server, in-process, for the tool list and resources. */\nasync function connectLocalReactorMcp(): Promise<Client> {\n const server = await createServer({ client: reactorlessClient });\n const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();\n await server.connect(serverSide);\n const client = new Client({ name: \"ph-mcp\", version: getVersion() });\n await client.connect(clientSide);\n return client;\n}\n\nfunction toolError(message: string): CallToolResult {\n return { isError: true, content: [{ type: \"text\", text: message }] };\n}\n\n/** The call never reached a live session: Vetra is down, or restarted since. */\nfunction isStaleConnection(error: unknown): boolean {\n if (error instanceof StreamableHTTPError) {\n return error.code === 404 || error.code === 400;\n }\n for (let e = error; e instanceof Error; e = e.cause) {\n if ((e as NodeJS.ErrnoException).code === \"ECONNREFUSED\") return true;\n }\n return false;\n}\n\nexport const RESTART_VETRA_TOOL = \"restartVetra\";\n\nconst restartVetraTool: Tool = {\n name: RESTART_VETRA_TOOL,\n description:\n \"Restart this project's Vetra (its Switchboard and Studio) and wait until it is ready. \" +\n \"Use it after a change Vetra reads only at startup, such as the reactor or packages settings \" +\n \"in powerhouse.config.json; Studio restarts by itself for connect.* changes. \" +\n \"Returns the new Connect, Switchboard and MCP URLs.\",\n inputSchema: { type: \"object\", properties: {} },\n outputSchema: {\n type: \"object\",\n properties: {\n pid: { type: \"number\" },\n connectUrl: { type: \"string\" },\n switchboardUrl: { type: \"string\" },\n mcpUrl: { type: \"string\" },\n },\n required: [\"pid\", \"mcpUrl\"],\n },\n};\n\nfunction vetraUrls(record: VetraRuntimeRecord) {\n return {\n pid: record.pid,\n ...(record.connectUrl ? { connectUrl: record.connectUrl } : {}),\n switchboardUrl:\n record.switchboardUrl ??\n `http://localhost:${record.switchboardPort}/graphql`,\n mcpUrl: record.mcpUrl || `http://localhost:${record.switchboardPort}/mcp`,\n };\n}\n\nfunction projectName(projectDir: string): string | undefined {\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(projectDir, \"package.json\"), \"utf8\"),\n ) as { name?: string };\n return pkg.name;\n } catch {\n return undefined;\n }\n}\n\n/** Connects to the project's Vetra `/mcp`, starting Vetra when it is down. */\ntype Progress = (message: string) => void;\n\nclass Upstream {\n #client: Promise<Client> | undefined;\n /** The Vetra the client talks to; another pid in the record means it restarted. */\n #pid: number | undefined;\n /** The calls waiting on the connection, told how Vetra's start goes. */\n #waiting = new Set<Progress>();\n\n constructor(\n private readonly projectDir: string | undefined,\n private readonly options: McpLauncherOptions,\n ) {}\n\n get(onProgress?: Progress): Promise<Client> {\n if (this.#client && this.#pid !== undefined && this.projectDir) {\n const pid = readVetraRuntime(this.projectDir)?.pid;\n if (pid !== this.#pid) this.reset();\n }\n this.#client ??= this.#connect(ensureVetra).catch((error: unknown) => {\n this.#client = undefined;\n throw error;\n });\n return this.#waitWith(this.#client, onProgress);\n }\n\n async #waitWith<T>(task: Promise<T>, onProgress?: Progress): Promise<T> {\n if (onProgress) this.#waiting.add(onProgress);\n try {\n return await task;\n } finally {\n if (onProgress) this.#waiting.delete(onProgress);\n }\n }\n\n #report = (message: string) => {\n for (const progress of this.#waiting) progress(message);\n };\n\n reset(): void {\n const stale = this.#client;\n this.#client = undefined;\n this.#pid = undefined;\n void stale?.then((client) => client.close()).catch(() => {});\n }\n\n /** Restarts Vetra and connects to the new one; resolves to its record. */\n async restart(onProgress?: Progress): Promise<VetraRuntimeRecord> {\n this.reset();\n let record: VetraRuntimeRecord | undefined;\n const connected = this.#connect(async (options) => {\n record = await restartVetra(options);\n return record;\n });\n this.#client = connected.catch((error: unknown) => {\n this.#client = undefined;\n throw error;\n });\n await this.#waitWith(this.#client, onProgress);\n return record!;\n }\n\n async #connect(\n start: (options: EnsureVetraOptions) => Promise<VetraRuntimeRecord>,\n ): Promise<Client> {\n const { projectDir } = this;\n if (!projectDir) {\n throw new VetraStartError(\n `No Powerhouse project (${CONFIG_FILE}) at or above ${process.cwd()}. Run \\`ph mcp\\` inside the project, or pass --project-dir.`,\n );\n }\n const name = projectName(projectDir);\n if (!name) {\n throw new VetraStartError(`${projectDir} has no package.json name.`);\n }\n console.error(`[ph mcp] connecting to Vetra for ${name}...`);\n const record = await start({\n projectDir,\n projectName: name,\n switchboardPort: resolveSwitchboardPortDefault(),\n command: this.options.vetraCommand ?? currentPhCliVetraCommand(),\n timeoutMs: this.options.startTimeoutSeconds * 1000,\n onProgress: this.#report,\n });\n const { mcpUrl } = vetraUrls(record);\n const client = new Client({ name: \"ph-mcp\", version: getVersion() });\n await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl)));\n this.#pid = record.pid;\n console.error(`[ph mcp] forwarding tool calls to ${mcpUrl}`);\n return client;\n }\n}\n\nasync function forwardToolCall(\n upstream: Upstream,\n params: CallToolRequest[\"params\"],\n signal: AbortSignal,\n onProgress: Progress,\n): Promise<CallToolResult> {\n for (let attempt = 0; ; attempt++) {\n const client = await upstream.get(onProgress);\n try {\n return await client.request(\n { method: \"tools/call\", params },\n CallToolResultSchema,\n { signal, timeout: CALL_TIMEOUT_MS },\n );\n } catch (error) {\n // It never arrived: Vetra went away or restarted, so find or start it again.\n if (attempt > 0 || !isStaleConnection(error)) throw error;\n upstream.reset();\n }\n }\n}\n\n/** `ph mcp`: tools listed by in-process reactor-mcp, calls forwarded to Vetra (started on first call). */\nexport async function startMcpLauncher(options: McpLauncherOptions) {\n // stdout carries JSON-RPC only.\n console.log = console.error;\n console.info = console.error;\n\n const projectDir = findProjectDir(\n options.projectDir ?? process.env.PH_CALLER_CWD ?? process.cwd(),\n );\n // Port resolution and `ph vetra` both read the project from the cwd.\n if (projectDir) process.chdir(projectDir);\n\n const local = await connectLocalReactorMcp();\n const upstream = new Upstream(projectDir, options);\n const server = new Server(\n local.getServerVersion() ?? { name: \"reactor-mcp-server\", version: \"\" },\n {\n capabilities: { tools: {}, resources: {} },\n instructions: local.getInstructions(),\n },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async (request) => {\n const listed = await local.listTools(request.params);\n return { ...listed, tools: [...listed.tools, restartVetraTool] };\n });\n server.setRequestHandler(ListResourcesRequestSchema, (request) =>\n local.listResources(request.params),\n );\n server.setRequestHandler(ListResourceTemplatesRequestSchema, (request) =>\n local.listResourceTemplates(request.params),\n );\n server.setRequestHandler(ReadResourceRequestSchema, (request) =>\n local.readResource(request.params),\n );\n server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\n // How Vetra's start goes: progress notifications when the client asked, else stderr.\n const token = request.params._meta?.progressToken;\n let progress = 0;\n const onProgress: Progress = (message) => {\n if (token === undefined) {\n console.error(`[ph mcp] ${message}`);\n return;\n }\n void extra\n .sendNotification({\n method: \"notifications/progress\",\n params: { progressToken: token, progress: ++progress, message },\n })\n .catch(() => {});\n };\n try {\n if (request.params.name === RESTART_VETRA_TOOL) {\n const urls = vetraUrls(await upstream.restart(onProgress));\n return {\n content: [{ type: \"text\", text: JSON.stringify(urls) }],\n structuredContent: urls,\n };\n }\n return await forwardToolCall(\n upstream,\n request.params,\n extra.signal,\n onProgress,\n );\n } catch (error) {\n // Protocol errors from reactor-mcp reach the agent as they would over HTTP.\n if (error instanceof McpError) throw error;\n const message = error instanceof Error ? error.message : String(error);\n return toolError(\n error instanceof VetraStartError\n ? message\n : `reactor-mcp request failed: ${message}`,\n );\n }\n });\n\n const transport = new StdioServerTransport();\n transport.onclose = () => process.exit(0);\n process.stdin.once(\"end\", () => process.exit(0));\n await server.connect(transport);\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAuCA,MAAM,kBAAkB;AACxB,MAAM,cAAc;;AAUpB,SAAgB,eAAe,OAAmC;CAChE,IAAI,MAAM,KAAK,QAAQ,KAAK;CAC5B,SAAS;EACP,IAAI,GAAG,WAAW,KAAK,KAAK,KAAK,WAAW,CAAC,GAAG,OAAO;EACvD,MAAM,SAAS,KAAK,QAAQ,GAAG;EAC/B,IAAI,WAAW,KAAK,OAAO,KAAA;EAC3B,MAAM;CACR;AACF;AAGA,MAAM,oBAAoB,IAAI,MAAM,CAAC,GAAqB,EACxD,IAAI,SAAS,UAAU;CACrB,IAAI,aAAa,QAAQ,OAAO,KAAA;CAChC,aAAa;EACX,MAAM,IAAI,MAAM,8CAA8C;CAChE;AACF,EACF,CAAC;;AAGD,eAAe,yBAA0C;CACvD,MAAM,SAAS,MAAM,aAAa,EAAE,QAAQ,kBAAkB,CAAC;CAC/D,MAAM,CAAC,YAAY,cAAc,kBAAkB,iBAAiB;CACpE,MAAM,OAAO,QAAQ,UAAU;CAC/B,MAAM,SAAS,IAAI,OAAO;EAAE,MAAM;EAAU,SAAS,WAAW;CAAE,CAAC;CACnE,MAAM,OAAO,QAAQ,UAAU;CAC/B,OAAO;AACT;AAEA,SAAS,UAAU,SAAiC;CAClD,OAAO;EAAE,SAAS;EAAM,SAAS,CAAC;GAAE,MAAM;GAAQ,MAAM;EAAQ,CAAC;CAAE;AACrE;;AAGA,SAAS,kBAAkB,OAAyB;CAClD,IAAI,iBAAiB,qBACnB,OAAO,MAAM,SAAS,OAAO,MAAM,SAAS;CAE9C,K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qCAAqC,YAC5D,MAAM,sBAAsB,QAAQ,MAAM,CAC5C;CACA,OAAO,kBAAkB,4BAA4B,YACnD,MAAM,aAAa,QAAQ,MAAM,CACnC;CACA,OAAO,kBAAkB,uBAAuB,OAAO,SAAS,UAAU;EAExE,MAAM,QAAQ,QAAQ,OAAO,OAAO;EACpC,IAAI,WAAW;EACf,MAAM,cAAwB,YAAY;GACxC,IAAI,UAAU,KAAA,GAAW;IACvB,QAAQ,MAAM,YAAY,SAAS;IACnC;GACF;GACA,MACG,iBAAiB;IAChB,QAAQ;IACR,QAAQ;KAAE,eAAe;KAAO,UAAU,EAAE;KAAU;IAAQ;GAChE,CAAC,CAAC,CACD,YAAY,CAAC,CAAC;EACnB;EACA,IAAI;GACF,IAAI,QAAQ,OAAO,SAAA,gBAA6B;IAC9C,MAAM,OAAO,UAAU,MAAM,SAAS,QAAQ,UAAU,CAAC;IACzD,OAAO;KACL,SAAS,CAAC;MAAE,MAAM;MAAQ,MAAM,KAAK,UAAU,IAAI;KAAE,CAAC;KACtD,mBAAmB;IACrB;GACF;GACA,OAAO,MAAM,gBACX,UACA,QAAQ,QACR,MAAM,QACN,UACF;EACF,SAAS,OAAO;GAEd,IAAI,iBAAiB,UAAU,MAAM;GACrC,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACrE,OAAO,UACL,iBAAiB,kBACb,UACA,+BAA+B,SACrC;EACF;CACF,CAAC;CAED,MAAM,YAAY,IAAI,qBAAqB;CAC3C,UAAU,gBAAgB,QAAQ,KAAK,CAAC;CACxC,QAAQ,MAAM,KAAK,aAAa,QAAQ,KAAK,CAAC,CAAC;CAC/C,MAAM,OAAO,QAAQ,SAAS;AAChC","debug_id":"3bb6193f-0a25-5eb5-8077-3f3b52ec8b22"}
@@ -1,5 +1,5 @@
1
1
 
2
- !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]="1b5fed19-b3c9-5431-95f2-c5fde8a3cac2")}catch(e){}}();
2
+ !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]="47c22c00-4efb-583d-9f80-533dc2b02026")}catch(e){}}();
3
3
  import { l as primaryBackend, m as reactorBlockToSwitchboardConfig, p as protocolEnv, t as assertProtocolConsistency } from "./dist-BfUgk19n.mjs";
4
4
  import fs from "node:fs";
5
5
  import path from "node:path";
@@ -63,6 +63,7 @@ const memberSwitchboardConfigSchema = switchboardConfigLayerSchema([
63
63
  "storage.reactor",
64
64
  "storage.readModel",
65
65
  "protocol",
66
+ "telemetry",
66
67
  "packages.dynamic",
67
68
  "drive",
68
69
  "remoteDrives",
@@ -150,5 +151,5 @@ function switchboardDevMode(devVerb, runner) {
150
151
  //#endregion
151
152
  export { reactorBlockConflicts as a, switchboardDevMode as c, prepareMemberStorage as i, memberSwitchboardConfig as n, readModelAsReactorStore as o, memberSwitchboardConfigSchema as r, rememberShellNames as s, memberEnvOf as t };
152
153
 
153
- //# sourceMappingURL=member-config-BShHC35u.mjs.map
154
- //# debugId=1b5fed19-b3c9-5431-95f2-c5fde8a3cac2
154
+ //# sourceMappingURL=member-config-CLziqSGm.mjs.map
155
+ //# debugId=47c22c00-4efb-583d-9f80-533dc2b02026
@@ -0,0 +1 @@
1
+ {"version":3,"file":"member-config-CLziqSGm.mjs","sources":["../src/runners/member-config.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n assertProtocolConsistency,\n primaryBackend,\n protocolEnv,\n reactorBlockToSwitchboardConfig,\n type ReactorConfig,\n} from \"@powerhousedao/host-core\";\nimport {\n mergeSwitchboardConfig,\n switchboardConfigLayerSchema,\n type SwitchboardConfigInput,\n} from \"@powerhousedao/switchboard/config\";\nimport {\n envNamesBeforeProjectEnv,\n isDotenvDisabled,\n} from \"@powerhousedao/shared/clis/project-env\";\nimport type { ILogger } from \"document-model\";\nimport dotenv from \"dotenv\";\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\n/** The operator's env, split by where each value came from. */\nexport interface MemberEnv {\n /** Set by the shell: wins over the host file. */\n shell: Env;\n /** Only in the project `.env`: the host file's keys win over these. */\n dotenv: Env;\n}\n\n// The server's dotenv.config() ignores a file it cannot read.\nfunction readDotenv(cwd: string): Record<string, string> {\n try {\n return dotenv.parse(fs.readFileSync(path.join(cwd, \".env\")));\n } catch {\n return {};\n }\n}\n\nconst shellNamesByEnv = new WeakMap<object, ReadonlySet<string>>();\n\n/** Records which names of `env` the shell set, before a `.env` loads into it. */\nexport function rememberShellNames(env: Env, names: Iterable<string>): void {\n shellNamesByEnv.set(env, new Set(names));\n}\n\n// Taken the first time an env is seen: before the first member's server\n// import loads the .env into it, and reused for every later member.\nfunction shellNamesOf(env: Env): ReadonlySet<string> {\n let names = shellNamesByEnv.get(env);\n if (!names) {\n names =\n (env === process.env ? envNamesBeforeProjectEnv() : undefined) ??\n new Set(Object.keys(env));\n shellNamesByEnv.set(env, names);\n }\n return names;\n}\n\n/**\n * Splits `env` into the shell's values and the `.env` the switchboard server\n * loads from `cwd` (the same file). A name the shell set stays the shell's,\n * whatever the file says.\n */\nexport function memberEnvOf(env: Env, cwd: string = process.cwd()): MemberEnv {\n const file = isDotenvDisabled({ ...env }) ? {} : readDotenv(cwd);\n const shellNames = shellNamesOf(env);\n const shell: Record<string, string | undefined> = {};\n for (const [name, value] of Object.entries(env)) {\n if (file[name] === undefined || shellNames.has(name)) shell[name] = value;\n }\n const fromFile: Record<string, string> = {};\n for (const [name, value] of Object.entries(file)) {\n if (!shellNames.has(name)) fromFile[name] = value;\n }\n return { shell, dotenv: fromFile };\n}\n\n/** The env vars the block sets, which a `.env` value does not override. */\nfunction blockEnvNames(reactor: ReactorConfig | undefined): string[] {\n const block = reactorBlockToSwitchboardConfig(reactor);\n return [\n ...Object.keys(protocolEnv(reactor?.protocol)),\n ...(block.packages?.dynamic ? [\"DYNAMIC_MODEL_LOADING\"] : []),\n ...(block.features ? [\"PH_WORKFLOWS_ENABLED\"] : []),\n ];\n}\n\n/** `config.switchboard`: a member's own switchboard config. The omitted keys\n * live in the reactor block (storage, protocol, dynamic packages) or the\n * runner (port, dev verb, drives, plugins), or are process-wide or not JSON. */\nexport const memberSwitchboardConfigSchema = switchboardConfigLayerSchema([\n \"logLevel\",\n \"server.port\",\n \"server.dev\",\n \"storage.reactor\",\n \"storage.readModel\",\n \"protocol\",\n \"telemetry\",\n \"packages.dynamic\",\n \"drive\",\n \"remoteDrives\",\n \"features.pluginHost\",\n \"processorConfig\",\n]);\n\nexport interface SwitchboardMember {\n reactor?: ReactorConfig;\n config?: { switchboard?: SwitchboardConfigInput };\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\n/** The dotted keys both layers set. */\nexport function overlappingKeys(\n a: Record<string, unknown>,\n b: Record<string, unknown>,\n path = \"\",\n): string[] {\n return Object.entries(b).flatMap(([key, value]) => {\n const other = a[key];\n if (value === undefined || other === undefined) return [];\n const at = path ? `${path}.${key}` : key;\n return isPlainObject(value) && isPlainObject(other)\n ? overlappingKeys(other, value, at)\n : [at];\n });\n}\n\n/** Each `config.switchboard` key the reactor block already sets. */\nexport function reactorBlockConflicts(member: SwitchboardMember): string[] {\n const own = member.config?.switchboard;\n if (!own) return [];\n return overlappingKeys(\n reactorBlockToSwitchboardConfig(member.reactor) as Record<string, unknown>,\n own as Record<string, unknown>,\n ).map(\n (key) =>\n `config.switchboard.${key} is also set by the reactor block; set it in one place.`,\n );\n}\n\n/**\n * The deprecation notice for a block whose `readModel.url` still names the\n * reactor store too: nothing else names the store, as it did when\n * readModel.url rode `dbPath`.\n */\nexport function readModelAsReactorStore(\n reactor: ReactorConfig | undefined,\n env: Env,\n hostFileLabel: string,\n): { url: string; warning: string } | undefined {\n const storage = reactorBlockToSwitchboardConfig(reactor).storage;\n const url = storage?.readModel?.url;\n if (\n !url ||\n storage.reactor ||\n env.PH_REACTOR_DATABASE_URL !== undefined ||\n env.PH_SWITCHBOARD_DATABASE_URL !== undefined\n ) {\n return undefined;\n }\n return {\n url,\n warning:\n `${hostFileLabel}: reactor readModel.url (${url}) also holds the reactor store, because no storage names one. ` +\n \"This is deprecated: set the backend's storage explicitly (the same Postgres url, or a path dataDir).\",\n };\n}\n\n/**\n * The member's switchboard config under the runner's own arguments: its\n * reactor block, then `config.switchboard`, then the env over both, mapped\n * once as the server read it (the shell over the `.env`, whose values for the\n * block's own vars are dropped). The block keeps the precedence it had as\n * set-if-absent env and `dbPath`: only a shell PH_REACTOR_DATABASE_URL\n * overrides its store, and no env var overrides its read model. Writes nothing.\n */\nexport async function memberSwitchboardConfig(\n member: SwitchboardMember,\n env: MemberEnv,\n options: {\n pluginHost: boolean;\n logger?: ILogger;\n /** Under everything else: values no flag or host file set. */\n defaults?: SwitchboardConfigInput;\n },\n): Promise<SwitchboardConfigInput> {\n // Lazy: the env mapping loads reactor-api, which the runner module must not.\n const { switchboardConfigFromEnv } =\n await import(\"@powerhousedao/switchboard/config/env\");\n const block = reactorBlockToSwitchboardConfig(member.reactor);\n const legacy = readModelAsReactorStore(member.reactor, env.shell, \"\");\n if (legacy) {\n block.storage = { ...block.storage, reactor: { url: legacy.url } };\n }\n // One env, as the server read it: the .env under the block's own vars,\n // the shell over both.\n const dotenvValues: Record<string, string | undefined> = { ...env.dotenv };\n for (const name of blockEnvNames(member.reactor)) delete dotenvValues[name];\n const fromEnv = switchboardConfigFromEnv(\n { ...dotenvValues, ...env.shell },\n { logger: options.logger },\n );\n const storage = { ...fromEnv.storage };\n if (\n block.storage?.reactor &&\n env.shell.PH_REACTOR_DATABASE_URL === undefined\n ) {\n delete storage.reactor;\n }\n if (block.storage?.readModel) delete storage.readModel;\n return mergeSwitchboardConfig(\n options.defaults ?? {},\n block,\n member.config?.switchboard ?? {},\n { ...fromEnv, storage },\n // A declared composition turns the plugin host on, whatever the env says.\n options.pluginHost ? { features: { pluginHost: true } } : {},\n );\n}\n\n/**\n * Fails when the operator's env contradicts the member's protocol block, then\n * creates the block's path-storage dir (the server's own mkdir is not\n * recursive).\n */\nexport function prepareMemberStorage(\n reactor: ReactorConfig | undefined,\n env: Env,\n hostFileLabel: string,\n): void {\n assertProtocolConsistency(reactor?.protocol, { ...env }, hostFileLabel);\n const storage = primaryBackend(reactor)?.storage;\n if (storage?.kind !== \"path\" || !storage.dataDir) return;\n // `ph run` resolves `$env` and the `${userData}` sugar before the verb;\n // an unresolved one here would mkdir a literal \"${userData}\" folder.\n if (/\\$\\{(userData|projectRoot)\\}/.test(storage.dataDir)) {\n throw new Error(\n `${hostFileLabel}: storage.dataDir \"${storage.dataDir}\" was not resolved; resolve the host (resolveHostOutputs) before starting it.`,\n );\n }\n fs.mkdirSync(storage.dataDir, { recursive: true });\n}\n\n/** The verb owns dev mode; `runner.dev` is the host-file spelling of it. */\nexport function switchboardDevMode(\n devVerb: boolean,\n runner: { dev?: boolean },\n): boolean {\n return devVerb || runner.dev === true;\n}\n"],"names":[],"mappings":";;;;;;;;;AAgCA,SAAS,WAAW,KAAqC;CACvD,IAAI;EACF,OAAO,OAAO,MAAM,GAAG,aAAa,KAAK,KAAK,KAAK,MAAM,CAAC,CAAC;CAC7D,QAAQ;EACN,OAAO,CAAC;CACV;AACF;AAEA,MAAM,kCAAkB,IAAI,QAAqC;;AAGjE,SAAgB,mBAAmB,KAAU,OAA+B;CAC1E,gBAAgB,IAAI,KAAK,IAAI,IAAI,KAAK,CAAC;AACzC;AAIA,SAAS,aAAa,KAA+B;CACnD,IAAI,QAAQ,gBAAgB,IAAI,GAAG;CACnC,IAAI,CAAC,OAAO;EACV,SACG,QAAQ,QAAQ,MAAM,yBAAyB,I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AO,QAAQ;CAEjB,IAAI,MAAM,SAAS,WAAW,OAAO,QAAQ;CAC7C,OAAO,uBACL,QAAQ,YAAY,CAAC,GACrB,OACA,OAAO,QAAQ,eAAe,CAAC,GAC/B;EAAE,GAAG;EAAS;CAAQ,GAEtB,QAAQ,aAAa,EAAE,UAAU,EAAE,YAAY,KAAK,EAAE,IAAI,CAAC,CAC7D;AACF;;;;;;AAOA,SAAgB,qBACd,SACA,KACA,eACM;CACN,0BAA0B,SAAS,UAAU,EAAE,GAAG,IAAI,GAAG,aAAa;CACtE,MAAM,UAAU,eAAe,OAAO,CAAC,EAAE;CACzC,IAAI,SAAS,SAAS,UAAU,CAAC,QAAQ,SAAS;CAGlD,IAAI,+BAA+B,KAAK,QAAQ,OAAO,GACrD,MAAM,IAAI,MACR,GAAG,cAAc,qBAAqB,QAAQ,QAAQ,8EACxD;CAEF,GAAG,UAAU,QAAQ,SAAS,EAAE,WAAW,KAAK,CAAC;AACnD;;AAGA,SAAgB,mBACd,SACA,QACS;CACT,OAAO,WAAW,OAAO,QAAQ;AACnC","debug_id":"47c22c00-4efb-583d-9f80-533dc2b02026"}
@@ -0,0 +1,4 @@
1
+ import { n as phCliCommands } from "./ph-cli-commands-DoB_GolD.mjs";
2
+ export { phCliCommands };
3
+ !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]="5a949395-481b-534d-8641-0c6c9a99d4ae")}catch(e){}}();
4
+ //# debugId=5a949395-481b-534d-8641-0c6c9a99d4ae
@@ -1,9 +1,9 @@
1
1
 
2
- !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]="af75352e-31b9-56ef-a4a6-effe7d7c36c8")}catch(e){}}();
2
+ !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]="a2540374-fc56-5426-9197-567e24e89258")}catch(e){}}();
3
3
  import { n as skipInstallArgs } from "./install-added-dependencies-DnZFR3aE.mjs";
4
4
  import { t as isUniformRunnersEnabled } from "./feature-flags-xwqcHEWC.mjs";
5
5
  import { boolean, command, extendType, flag, multioption, number, oneOf, option, optional, positional, string, subcommands } from "cmd-ts";
6
- import { AGENTS, accessTokenArgs, buildArgs, connectBuildArgs, connectConfigArgs, connectPreviewArgs, connectStudioArgs, debugArgs, hostCheckArgs, hostExportArgs, initArgs, inspectArgs, installArgs, listArgs, loginArgs, mcpArgs, migrateArgs, publishArgs, registryLoginArgs, switchboardArgs, uninstallArgs, unpublishArgs, vetraArgs } from "@powerhousedao/shared/clis/args";
6
+ import { AGENTS, accessTokenArgs, buildArgs, connectBuildArgs, connectConfigArgs, connectPreviewArgs, connectStudioArgs, debugArgs, hostCheckArgs, hostExportArgs, initArgs, inspectArgs, installArgs, keyframesArgs, listArgs, loginArgs, mcpArgs, migrateArgs, publishArgs, registryLoginArgs, switchboardArgs, uninstallArgs, unpublishArgs, vetraArgs } from "@powerhousedao/shared/clis/args";
7
7
  import { DEFAULT_EXPIRY_SECONDS } from "@powerhousedao/shared/clis/constants";
8
8
  import fs from "node:fs";
9
9
  import path from "node:path";
@@ -770,7 +770,7 @@ const check = command({
770
770
  description: "Check a host the way `ph run` would, without starting it: every load, validation, resolution and boot issue, grouped by host file. Exits 1 on any issue. `--env <file>` checks against that file alone.",
771
771
  args: hostCheckArgs,
772
772
  handler: async (args) => {
773
- const { runHostCheck } = await import("./check-BWRbBScq.mjs");
773
+ const { runHostCheck } = await import("./check-o9kpHrG_.mjs");
774
774
  const { output, exitCode } = await runHostCheck(args);
775
775
  console.log(output);
776
776
  process.exitCode = exitCode;
@@ -945,6 +945,36 @@ Resolution order for the registry URL:
945
945
  }
946
946
  });
947
947
  //#endregion
948
+ //#region src/commands/keyframes.ts
949
+ const keyframes = command({
950
+ name: "keyframes",
951
+ description: `
952
+ The keyframes command reports on and cleans up the keyframes of a running switchboard,
953
+ through its inspection-admin endpoint.
954
+
955
+ Prerequisites:
956
+ - The host serves inspection-admin (INSPECTION_ADMIN_ENABLED=true).
957
+ - The caller is one of the host's auth admins.
958
+ - The keep rules are in powerhouse.config.json under reactor.keyframes, or in PH_KEYFRAMES.
959
+
960
+ Run preview first: it only reads. clean then removes the keyframes past each type's keep
961
+ count and all keyframes of deleted documents, in small paced statements beside live
962
+ traffic. Running it again is safe. A later read that misses a keyframe replays from the
963
+ operation log, so a clean-up costs time on cold reads and never changes a document.
964
+
965
+ The disk only shrinks after reclaim, which rewrites the Keyframe table once the store is
966
+ quiet. On PGlite the store answers nothing while it rewrites. On Postgres it says what to
967
+ run by hand.
968
+ `,
969
+ args: keyframesArgs,
970
+ handler: async (args) => {
971
+ if (args.debug) console.log(args);
972
+ const { runKeyframesCommand } = await import("./keyframes-bFo9iDhT.mjs");
973
+ const exitCode = await runKeyframesCommand(args);
974
+ process.exit(exitCode);
975
+ }
976
+ });
977
+ //#endregion
948
978
  //#region src/commands/list.ts
949
979
  const list = command({
950
980
  name: "list",
@@ -1116,7 +1146,7 @@ way (\`ph vetra --restart\`), the next tool call connects to the new one.
1116
1146
  `,
1117
1147
  handler: async (args) => {
1118
1148
  if (args.debug) console.error(args);
1119
- const { startMcpLauncher } = await import("./mcp-DzxVWwmn.mjs");
1149
+ const { startMcpLauncher } = await import("./mcp-tMRVrU0l.mjs");
1120
1150
  await startMcpLauncher({
1121
1151
  projectDir: args.projectDir,
1122
1152
  startTimeoutSeconds: args.startTimeout
@@ -1584,6 +1614,7 @@ by itself when powerhouse.config.json changes.
1584
1614
  "access-token": accessToken,
1585
1615
  "registry-login": registryLogin,
1586
1616
  inspect,
1617
+ keyframes,
1587
1618
  list,
1588
1619
  mcp,
1589
1620
  migrate,
@@ -1606,5 +1637,5 @@ const phCliCommands = buildPhCliCommands(isUniformRunnersEnabled());
1606
1637
  //#endregion
1607
1638
  export { phCliCommands as n, buildPhCliCommands as t };
1608
1639
 
1609
- //# sourceMappingURL=ph-cli-commands-CkN8Mx1U.mjs.map
1610
- //# debugId=af75352e-31b9-56ef-a4a6-effe7d7c36c8
1640
+ //# sourceMappingURL=ph-cli-commands-DoB_GolD.mjs.map
1641
+ //# debugId=a2540374-fc56-5426-9197-567e24e89258