@powerhousedao/ph-cli 6.4.0-next.2 → 6.4.0-next.5

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 (146) hide show
  1. package/README.md +6 -5
  2. package/dist/auth-5bqHASGL.mjs +4 -0
  3. package/dist/auth-DYknkWfW.mjs +23 -0
  4. package/dist/auth-DYknkWfW.mjs.map +1 -0
  5. package/dist/{build-C7RBpPwa.mjs → build-CBKlv5E3.mjs} +6 -6
  6. package/dist/{build-C7RBpPwa.mjs.map → build-CBKlv5E3.mjs.map} +1 -1
  7. package/dist/build-Dr1lnv4h.mjs +4 -0
  8. package/dist/{check-1Hfe0lVO.mjs → check-CW81vbe9.mjs} +4 -4
  9. package/dist/{check-1Hfe0lVO.mjs.map → check-CW81vbe9.mjs.map} +1 -1
  10. package/dist/{check-MBdw9Lbm.mjs → check-Cx_AeBQe.mjs} +7 -7
  11. package/dist/check-Cx_AeBQe.mjs.map +1 -0
  12. package/dist/{check-ClxYRer4.mjs → check-DhFd9tO8.mjs} +3 -3
  13. package/dist/{cli-connect-override-DsuuectH.mjs → cli-connect-override-DKxY3lCi.mjs} +4 -4
  14. package/dist/{cli-connect-override-DsuuectH.mjs.map → cli-connect-override-DKxY3lCi.mjs.map} +1 -1
  15. package/dist/cli.mjs +9 -8
  16. package/dist/cli.mjs.map +1 -1
  17. package/dist/{compound-Q9sZSEZF-zZWzQ7VC.mjs → compound-g6x_KkWp-Bs7olmlI.mjs} +464 -360
  18. package/dist/compound-g6x_KkWp-Bs7olmlI.mjs.map +1 -0
  19. package/dist/{connect-build-DAnGPSF5.mjs → connect-build-DpGUrtct.mjs} +5 -5
  20. package/dist/{connect-build-DAnGPSF5.mjs.map → connect-build-DpGUrtct.mjs.map} +1 -1
  21. package/dist/{connect-config-C0QZ7zTf.mjs → connect-config-BpzwJln3.mjs} +4 -4
  22. package/dist/{connect-config-C0QZ7zTf.mjs.map → connect-config-BpzwJln3.mjs.map} +1 -1
  23. package/dist/{connect-preview-BvxXGo_W.mjs → connect-preview-B_E4SIV6.mjs} +21 -4
  24. package/dist/connect-preview-B_E4SIV6.mjs.map +1 -0
  25. package/dist/connect-studio-BPZOcwUM.mjs +214 -0
  26. package/dist/connect-studio-BPZOcwUM.mjs.map +1 -0
  27. package/dist/credentials-CmtYywgk.mjs +132 -0
  28. package/dist/credentials-CmtYywgk.mjs.map +1 -0
  29. package/dist/definitions-worker.mjs +4 -4
  30. package/dist/definitions-worker.mjs.map +1 -1
  31. package/dist/dev-host-CM-Jg2kY.mjs +19 -0
  32. package/dist/dev-host-CM-Jg2kY.mjs.map +1 -0
  33. package/dist/{dist-CRR5Anp2.mjs → dist-DPj_FB8H.mjs} +5 -5
  34. package/dist/dist-DPj_FB8H.mjs.map +1 -0
  35. package/dist/{explain-BfOC7Ngv.mjs → explain-DQ5ymlco.mjs} +5 -5
  36. package/dist/{explain-BfOC7Ngv.mjs.map → explain-DQ5ymlco.mjs.map} +1 -1
  37. package/dist/{export-CdTqYviH.mjs → export-CzeF8pob.mjs} +4 -4
  38. package/dist/{export-CdTqYviH.mjs.map → export-CzeF8pob.mjs.map} +1 -1
  39. package/dist/{generate-all-HujZHqCG.mjs → generate-all-B9MwWXlq.mjs} +6 -21
  40. package/dist/generate-all-B9MwWXlq.mjs.map +1 -0
  41. package/dist/{generate-app-hm6CJ_4O.mjs → generate-app-C7n0j8Ak.mjs} +5 -18
  42. package/dist/generate-app-C7n0j8Ak.mjs.map +1 -0
  43. package/dist/{generate-document-model-BiD6ovXc.mjs → generate-document-model-D3LKY1D7.mjs} +11 -35
  44. package/dist/generate-document-model-D3LKY1D7.mjs.map +1 -0
  45. package/dist/{generate-editor-DBj_Pxwa.mjs → generate-editor-DKuRUeIt.mjs} +5 -18
  46. package/dist/generate-editor-DKuRUeIt.mjs.map +1 -0
  47. package/dist/{generate-processor-BVjOsfjJ.mjs → generate-processor-CwJvJDpd.mjs} +5 -18
  48. package/dist/generate-processor-CwJvJDpd.mjs.map +1 -0
  49. package/dist/{generate-subgraph-DJZCr0Tk.mjs → generate-subgraph-Q1VLh3SC.mjs} +13 -39
  50. package/dist/generate-subgraph-Q1VLh3SC.mjs.map +1 -0
  51. package/dist/{get-version-DAYhm6MX.mjs → get-version-CTP__ORu.mjs} +4 -4
  52. package/dist/{get-version-DAYhm6MX.mjs.map → get-version-CTP__ORu.mjs.map} +1 -1
  53. package/dist/identity-DXZFeQfC.mjs +137 -0
  54. package/dist/identity-DXZFeQfC.mjs.map +1 -0
  55. package/dist/{index-Bs1PfL3W.d.mts → index-aosqo7aM.d.mts} +5 -4
  56. package/dist/index-aosqo7aM.d.mts.map +1 -0
  57. package/dist/{inspect-CulIpVsF.mjs → inspect-BgKI8Fhd.mjs} +6 -6
  58. package/dist/{inspect-CulIpVsF.mjs.map → inspect-BgKI8Fhd.mjs.map} +1 -1
  59. package/dist/{keyframes-bFo9iDhT.mjs → keyframes-BkeORfEu.mjs} +4 -4
  60. package/dist/{keyframes-bFo9iDhT.mjs.map → keyframes-BkeORfEu.mjs.map} +1 -1
  61. package/dist/{mcp-rtMGg307.mjs → mcp-gcG7SW9L.mjs} +152 -10
  62. package/dist/mcp-gcG7SW9L.mjs.map +1 -0
  63. package/dist/{migrate-CWCJP19Q.mjs → migrate-BaWZhorc.mjs} +4 -4
  64. package/dist/{migrate-CWCJP19Q.mjs.map → migrate-BaWZhorc.mjs.map} +1 -1
  65. package/dist/{migrate-document-models-DTxM7D7p.mjs → migrate-document-models-DYmkJzq3.mjs} +5 -6
  66. package/dist/migrate-document-models-DYmkJzq3.mjs.map +1 -0
  67. package/dist/{migrate-subgraphs-_yRnF7xt.mjs → migrate-subgraphs-BUgTeHcm.mjs} +6 -7
  68. package/dist/migrate-subgraphs-BUgTeHcm.mjs.map +1 -0
  69. package/dist/migrate-subgraphs-ChhXynqd.mjs +4 -0
  70. package/dist/{ph-cli-commands-FLZClR4x.mjs → ph-cli-commands-B5VkGW99.mjs} +179 -190
  71. package/dist/ph-cli-commands-B5VkGW99.mjs.map +1 -0
  72. package/dist/ph-cli-commands-CGXSo1wx.mjs +4 -0
  73. package/dist/{registry-auth-Bm5AR-fB.mjs → registry-auth-C8D5cno2.mjs} +4 -4
  74. package/dist/{registry-auth-Bm5AR-fB.mjs.map → registry-auth-C8D5cno2.mjs.map} +1 -1
  75. package/dist/render-BQE20Cnd.mjs +4 -0
  76. package/dist/{render-SVfj3m8A.mjs → render-CQdi685k.mjs} +6 -6
  77. package/dist/render-CQdi685k.mjs.map +1 -0
  78. package/dist/{run-LRGy7zGo.mjs → run-C6Vha5VN.mjs} +3 -3
  79. package/dist/{run--de_-WAz.mjs → run-sVzTTEUx.mjs} +5 -36
  80. package/dist/run-sVzTTEUx.mjs.map +1 -0
  81. package/dist/{run-sugar-DUiDFl_T.mjs → run-sugar-BuxOaRzE.mjs} +16 -8
  82. package/dist/run-sugar-BuxOaRzE.mjs.map +1 -0
  83. package/dist/{run-sugar-YDxw0iV9.mjs → run-sugar-Dz-rpeMO.mjs} +3 -3
  84. package/dist/runners/connect.d.mts +20 -3
  85. package/dist/runners/connect.d.mts.map +1 -1
  86. package/dist/runners/connect.mjs +37 -15
  87. package/dist/runners/connect.mjs.map +1 -1
  88. package/dist/runners/switchboard.d.mts +1 -1
  89. package/dist/runners/switchboard.mjs +3 -3
  90. package/dist/scripts/generate-commands-docs.ts +12 -0
  91. package/dist/{subgraphs-7OYWwP-C.mjs → subgraphs-Bm9NHTCn.mjs} +5 -38
  92. package/dist/subgraphs-Bm9NHTCn.mjs.map +1 -0
  93. package/dist/{sugar-checks-BFu3sfFJ.mjs → sugar-checks-DL-J3l2y.mjs} +16 -15
  94. package/dist/sugar-checks-DL-J3l2y.mjs.map +1 -0
  95. package/dist/{verify-Dkb6K1fc.mjs → verify-BLn76w09.mjs} +4 -4
  96. package/dist/{verify-Dkb6K1fc.mjs.map → verify-BLn76w09.mjs.map} +1 -1
  97. package/dist/{vetra-gateway-BMzq0mqX.mjs → vetra-gateway-D30pZgha.mjs} +5 -5
  98. package/dist/{vetra-gateway-BMzq0mqX.mjs.map → vetra-gateway-D30pZgha.mjs.map} +1 -1
  99. package/dist/vetra-gateway-DE5Hc0Fp.mjs +4 -0
  100. package/dist/vetra-host-0rSW35_r.mjs +230 -0
  101. package/dist/vetra-host-0rSW35_r.mjs.map +1 -0
  102. package/dist/{vetra-launcher-Dq0tWyNW.mjs → vetra-launcher-6NKfi6Au.mjs} +56 -13
  103. package/dist/vetra-launcher-6NKfi6Au.mjs.map +1 -0
  104. package/dist/vetra-launcher-XMk_Hv0c.mjs +4 -0
  105. package/dist/{vetra-instance-CLUzbtbh.mjs → vetra-runtime-Bk6CW-BE.mjs} +6 -24
  106. package/dist/vetra-runtime-Bk6CW-BE.mjs.map +1 -0
  107. package/dist/warn-subgraph-type-conflicts-BZ4NwLx5.mjs +131 -0
  108. package/dist/warn-subgraph-type-conflicts-BZ4NwLx5.mjs.map +1 -0
  109. package/package.json +17 -16
  110. package/dist/auth-BFUq7CvE.mjs +0 -18
  111. package/dist/auth-BFUq7CvE.mjs.map +0 -1
  112. package/dist/auth-CNhbN5UM.mjs +0 -4
  113. package/dist/build-BUpe1j4m.mjs +0 -4
  114. package/dist/check-MBdw9Lbm.mjs.map +0 -1
  115. package/dist/compound-Q9sZSEZF-zZWzQ7VC.mjs.map +0 -1
  116. package/dist/connect-preview-BvxXGo_W.mjs.map +0 -1
  117. package/dist/connect-studio-BUth3UYP.mjs +0 -106
  118. package/dist/connect-studio-BUth3UYP.mjs.map +0 -1
  119. package/dist/dist-CRR5Anp2.mjs.map +0 -1
  120. package/dist/generate-all-HujZHqCG.mjs.map +0 -1
  121. package/dist/generate-app-hm6CJ_4O.mjs.map +0 -1
  122. package/dist/generate-document-model-BiD6ovXc.mjs.map +0 -1
  123. package/dist/generate-editor-DBj_Pxwa.mjs.map +0 -1
  124. package/dist/generate-processor-BVjOsfjJ.mjs.map +0 -1
  125. package/dist/generate-subgraph-DJZCr0Tk.mjs.map +0 -1
  126. package/dist/index-Bs1PfL3W.d.mts.map +0 -1
  127. package/dist/mcp-rtMGg307.mjs.map +0 -1
  128. package/dist/migrate-document-models-DTxM7D7p.mjs.map +0 -1
  129. package/dist/migrate-subgraphs-DcJjLMFd.mjs +0 -4
  130. package/dist/migrate-subgraphs-_yRnF7xt.mjs.map +0 -1
  131. package/dist/ph-cli-commands-CRwA1aVX.mjs +0 -4
  132. package/dist/ph-cli-commands-FLZClR4x.mjs.map +0 -1
  133. package/dist/render-3M3DwFzO.mjs +0 -4
  134. package/dist/render-SVfj3m8A.mjs.map +0 -1
  135. package/dist/run--de_-WAz.mjs.map +0 -1
  136. package/dist/run-sugar-DUiDFl_T.mjs.map +0 -1
  137. package/dist/subgraphs-7OYWwP-C.mjs.map +0 -1
  138. package/dist/sugar-checks-BFu3sfFJ.mjs.map +0 -1
  139. package/dist/vetra-gateway-BP6Catg4.mjs +0 -4
  140. package/dist/vetra-host-C37IGwBM.mjs +0 -94
  141. package/dist/vetra-host-C37IGwBM.mjs.map +0 -1
  142. package/dist/vetra-instance-CLUzbtbh.mjs.map +0 -1
  143. package/dist/vetra-launcher-CJ01qmS1.mjs +0 -4
  144. package/dist/vetra-launcher-Dq0tWyNW.mjs.map +0 -1
  145. package/dist/warn-subgraph-type-conflicts-BOHBmThq.mjs +0 -19
  146. package/dist/warn-subgraph-type-conflicts-BOHBmThq.mjs.map +0 -1
@@ -0,0 +1,137 @@
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]="cee9f7e8-d1fe-5e9e-b0c8-f66c5d03af19")}catch(e){}}();
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { IDENTITY_KEY_ENV, askPassword, changePseudonymPassword, identityDataDir, loginPaths, pseudonymLabel, readActiveIdentity, readPseudonym } from "@powerhousedao/shared/clis/identity";
6
+ //#region src/services/identity.ts
7
+ function keyLine(info) {
8
+ switch (info.source) {
9
+ case "env": return `${IDENTITY_KEY_ENV} (never written)`;
10
+ case "data-folder": return `${info.file} (this store's own)`;
11
+ default: return `${info.file} (copied into this store at its first signature)`;
12
+ }
13
+ }
14
+ /** What `ph whoami` prints for `info`. */
15
+ function describeIdentity(info) {
16
+ if (!info) return [
17
+ "Nobody yet: no Renown login, and no pseudonym on this computer.",
18
+ "A pseudonym is made, readable by you only, when something must be signed here.",
19
+ "`ph login` logs in with Renown."
20
+ ];
21
+ if (info.kind === "renown") {
22
+ const login = info.renown;
23
+ if (login.expired) return [`Your Renown login as ${login.label} expired on ${login.expiresAt}.`, "Nothing signs with it: run `ph login` again, or `ph logout` to act as your pseudonym."];
24
+ return [
25
+ `Logged in with Renown as ${login.label}`,
26
+ ` Address: ${login.address}`,
27
+ ...login.expiresAt ? [` Expires: ${login.expiresAt}`] : [],
28
+ ` Login: ${login.file}`
29
+ ];
30
+ }
31
+ return [
32
+ `${info.label} (no Renown login)`,
33
+ ` Address: ${info.address}`,
34
+ ` Key: ${keyLine(info)}`,
35
+ ` Password: ${info.encrypted ? "yes" : "no"}`,
36
+ ...info.differsFromHome ? [` Your default pseudonym is ${pseudonymLabel(info.differsFromHome)}; this store keeps its own, which wrote its documents.`] : []
37
+ ];
38
+ }
39
+ /** A login `ph login` wrote into the project before 6.4: no longer read. */
40
+ function projectLoginNotice(dataDir) {
41
+ const file = path.join(dataDir, ".ph", ".renown.json");
42
+ try {
43
+ if (!JSON.parse(fs.readFileSync(file, "utf8")).user) return void 0;
44
+ } catch {
45
+ return;
46
+ }
47
+ return `This project holds a login from before 6.4 in ${file}. It is no longer read; the upgrade step withdraws and removes it.`;
48
+ }
49
+ async function runWhoami(args, print = console.log) {
50
+ const dataDir = identityDataDir();
51
+ let info = readActiveIdentity({ dataDir });
52
+ let checked;
53
+ if (args.check && info?.kind === "renown" && !info.renown.expired) {
54
+ const { homeLoginRenown } = await import("@renown/sdk/identity");
55
+ checked = (await homeLoginRenown({ baseUrl: args.renownUrl })).user ? "valid" : "withdrawn";
56
+ info = readActiveIdentity({ dataDir });
57
+ }
58
+ if (args.json) {
59
+ print(JSON.stringify({
60
+ identity: info ?? null,
61
+ ...checked ? { renown: checked } : {}
62
+ }, null, 2));
63
+ return 0;
64
+ }
65
+ if (checked === "withdrawn") print("Renown no longer knows your login: it was withdrawn or has expired.");
66
+ for (const line of describeIdentity(info)) print(line);
67
+ if (checked === "valid") print(" Renown: still valid");
68
+ const notice = projectLoginNotice(dataDir);
69
+ if (notice) print(notice);
70
+ return 0;
71
+ }
72
+ async function runLogout(args, print = console.log) {
73
+ const paths = loginPaths();
74
+ if (!fs.existsSync(paths.file) && !fs.existsSync(paths.keypair)) print("Not logged in.");
75
+ else {
76
+ const { logoutHome } = await import("@renown/sdk/identity");
77
+ const { withdraw, removed } = await logoutHome({ renownUrl: args.renownUrl });
78
+ switch (withdraw.status) {
79
+ case "withdrawn":
80
+ print("Withdrew the login at Renown.");
81
+ break;
82
+ case "not-found":
83
+ print("Renown holds no such login any more.");
84
+ break;
85
+ case "refused": {
86
+ print(`Renown did not take this computer's key as proof (${withdraw.reason}).`);
87
+ print(`Withdraw it with your wallet at ${withdraw.revokeUrl} (opening it now).`);
88
+ const { openBrowser } = await import("@renown/sdk/node");
89
+ await openBrowser(withdraw.revokeUrl).catch(() => void 0);
90
+ break;
91
+ }
92
+ case "unavailable": print(`Could not withdraw the login at Renown: ${withdraw.reason}. It lapses ${withdraw.expiresAt ? `on ${withdraw.expiresAt}` : "at its expiry"}.`);
93
+ }
94
+ for (const file of removed) print(`Deleted ${file}`);
95
+ }
96
+ const now = readActiveIdentity({ dataDir: identityDataDir() });
97
+ print(now ? `Now acting as ${now.label}.` : "Now acting as your pseudonym, made at the first signature.");
98
+ return 0;
99
+ }
100
+ async function runIdentityPassword(args, print = console.log) {
101
+ const dataDir = identityDataDir();
102
+ if (readPseudonym({ dataDir })?.source === "env") {
103
+ print(`${IDENTITY_KEY_ENV} is set: that key has no file to protect.`);
104
+ return 1;
105
+ }
106
+ if (!process.stdin.isTTY) {
107
+ print("`ph identity password` asks for passwords: run it in a terminal.");
108
+ return 1;
109
+ }
110
+ let newPassword;
111
+ if (!args.remove) {
112
+ newPassword = await askPassword("New password: ");
113
+ if (!newPassword) {
114
+ print("An empty password: use --remove to remove the password.");
115
+ return 1;
116
+ }
117
+ if (await askPassword("Repeat it: ") !== newPassword) {
118
+ print("The two passwords differ; nothing changed.");
119
+ return 1;
120
+ }
121
+ }
122
+ const result = await changePseudonymPassword({
123
+ dataDir,
124
+ unlock: { interactive: true },
125
+ ...newPassword ? { newPassword } : {}
126
+ });
127
+ const label = pseudonymLabel(result.address);
128
+ print(result.created ? `Made your pseudonym ${label}${newPassword ? ", locked with the password" : ""}.` : newPassword ? `${label} is locked with the new password.` : `${label} has no password now: its files are readable by you only.`);
129
+ for (const file of result.written) print(` wrote ${file}`);
130
+ for (const file of result.missing) print(` not found (moved or deleted): ${file}`);
131
+ return 0;
132
+ }
133
+ //#endregion
134
+ export { projectLoginNotice, runIdentityPassword, runLogout, runWhoami };
135
+
136
+ //# sourceMappingURL=identity-DXZFeQfC.mjs.map
137
+ //# debugId=cee9f7e8-d1fe-5e9e-b0c8-f66c5d03af19
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity-DXZFeQfC.mjs","sources":["../src/services/identity.ts"],"sourcesContent":["import {\n askPassword,\n changePseudonymPassword,\n identityDataDir,\n type IdentityInfo,\n IDENTITY_KEY_ENV,\n loginPaths,\n pseudonymLabel,\n readActiveIdentity,\n readPseudonym,\n} from \"@powerhousedao/shared/clis/identity\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * `ph whoami`, `ph logout` and `ph identity`: who acts here, the Renown login\n * in the home folder, and the pseudonym when nobody is logged in.\n */\n\ntype Print = (line: string) => void;\n\nfunction keyLine(info: IdentityInfo): string {\n switch (info.source) {\n case \"env\":\n return `${IDENTITY_KEY_ENV} (never written)`;\n case \"data-folder\":\n return `${info.file} (this store's own)`;\n default:\n return `${info.file} (copied into this store at its first signature)`;\n }\n}\n\n/** What `ph whoami` prints for `info`. */\nexport function describeIdentity(info: IdentityInfo | undefined): string[] {\n if (!info) {\n return [\n \"Nobody yet: no Renown login, and no pseudonym on this computer.\",\n \"A pseudonym is made, readable by you only, when something must be signed here.\",\n \"`ph login` logs in with Renown.\",\n ];\n }\n if (info.kind === \"renown\") {\n const login = info.renown!;\n if (login.expired) {\n return [\n `Your Renown login as ${login.label} expired on ${login.expiresAt}.`,\n \"Nothing signs with it: run `ph login` again, or `ph logout` to act as your pseudonym.\",\n ];\n }\n return [\n `Logged in with Renown as ${login.label}`,\n ` Address: ${login.address}`,\n ...(login.expiresAt ? [` Expires: ${login.expiresAt}`] : []),\n ` Login: ${login.file}`,\n ];\n }\n return [\n `${info.label} (no Renown login)`,\n ` Address: ${info.address}`,\n ` Key: ${keyLine(info)}`,\n ` Password: ${info.encrypted ? \"yes\" : \"no\"}`,\n ...(info.differsFromHome\n ? [\n ` Your default pseudonym is ${pseudonymLabel(info.differsFromHome)}; this store keeps its own, which wrote its documents.`,\n ]\n : []),\n ];\n}\n\n/** A login `ph login` wrote into the project before 6.4: no longer read. */\nexport function projectLoginNotice(dataDir: string): string | undefined {\n const file = path.join(dataDir, \".ph\", \".renown.json\");\n try {\n const stored = JSON.parse(fs.readFileSync(file, \"utf8\")) as {\n user?: unknown;\n };\n if (!stored.user) return undefined;\n } catch {\n return undefined;\n }\n return `This project holds a login from before 6.4 in ${file}. It is no longer read; the upgrade step withdraws and removes it.`;\n}\n\nexport async function runWhoami(\n args: { json?: boolean; check?: boolean; renownUrl: string },\n print: Print = console.log,\n): Promise<number> {\n const dataDir = identityDataDir();\n let info = readActiveIdentity({ dataDir });\n let checked: \"valid\" | \"withdrawn\" | undefined;\n if (args.check && info?.kind === \"renown\" && !info.renown!.expired) {\n const { homeLoginRenown } = await import(\"@renown/sdk/identity\");\n // Revalidation logs out a login Renown no longer knows.\n const renown = await homeLoginRenown({ baseUrl: args.renownUrl });\n checked = renown.user ? \"valid\" : \"withdrawn\";\n info = readActiveIdentity({ dataDir });\n }\n if (args.json) {\n print(\n JSON.stringify(\n { identity: info ?? null, ...(checked ? { renown: checked } : {}) },\n null,\n 2,\n ),\n );\n return 0;\n }\n if (checked === \"withdrawn\") {\n print(\n \"Renown no longer knows your login: it was withdrawn or has expired.\",\n );\n }\n for (const line of describeIdentity(info)) print(line);\n if (checked === \"valid\") print(\" Renown: still valid\");\n const notice = projectLoginNotice(dataDir);\n if (notice) print(notice);\n return 0;\n}\n\nexport async function runLogout(\n args: { renownUrl: string },\n print: Print = console.log,\n): Promise<number> {\n const paths = loginPaths();\n if (!fs.existsSync(paths.file) && !fs.existsSync(paths.keypair)) {\n print(\"Not logged in.\");\n } else {\n const { logoutHome } = await import(\"@renown/sdk/identity\");\n const { withdraw, removed } = await logoutHome({\n renownUrl: args.renownUrl,\n });\n switch (withdraw.status) {\n case \"withdrawn\":\n print(\"Withdrew the login at Renown.\");\n break;\n case \"not-found\":\n print(\"Renown holds no such login any more.\");\n break;\n case \"refused\": {\n print(\n `Renown did not take this computer's key as proof (${withdraw.reason}).`,\n );\n print(\n `Withdraw it with your wallet at ${withdraw.revokeUrl} (opening it now).`,\n );\n const { openBrowser } = await import(\"@renown/sdk/node\");\n await openBrowser(withdraw.revokeUrl).catch(() => undefined);\n break;\n }\n case \"unavailable\":\n print(\n `Could not withdraw the login at Renown: ${withdraw.reason}. It lapses ${withdraw.expiresAt ? `on ${withdraw.expiresAt}` : \"at its expiry\"}.`,\n );\n break;\n case \"not-logged-in\":\n break;\n }\n for (const file of removed) print(`Deleted ${file}`);\n }\n const now = readActiveIdentity({ dataDir: identityDataDir() });\n print(\n now\n ? `Now acting as ${now.label}.`\n : \"Now acting as your pseudonym, made at the first signature.\",\n );\n return 0;\n}\n\nexport async function runIdentityPassword(\n args: { remove?: boolean },\n print: Print = console.log,\n): Promise<number> {\n const dataDir = identityDataDir();\n const info = readPseudonym({ dataDir });\n if (info?.source === \"env\") {\n print(`${IDENTITY_KEY_ENV} is set: that key has no file to protect.`);\n return 1;\n }\n if (!process.stdin.isTTY) {\n print(\"`ph identity password` asks for passwords: run it in a terminal.\");\n return 1;\n }\n let newPassword: string | undefined;\n if (!args.remove) {\n newPassword = await askPassword(\"New password: \");\n if (!newPassword) {\n print(\"An empty password: use --remove to remove the password.\");\n return 1;\n }\n if ((await askPassword(\"Repeat it: \")) !== newPassword) {\n print(\"The two passwords differ; nothing changed.\");\n return 1;\n }\n }\n const result = await changePseudonymPassword({\n dataDir,\n unlock: { interactive: true },\n ...(newPassword ? { newPassword } : {}),\n });\n const label = pseudonymLabel(result.address);\n print(\n result.created\n ? `Made your pseudonym ${label}${newPassword ? \", locked with the password\" : \"\"}.`\n : newPassword\n ? `${label} is locked with the new password.`\n : `${label} has no password now: its files are readable by you only.`,\n );\n for (const file of result.written) print(` wrote ${file}`);\n for (const file of result.missing)\n print(` not found (moved or deleted): ${file}`);\n return 0;\n}\n"],"names":[],"mappings":";;;;;;AAqBA,SAAS,QAAQ,MAA4B;CAC3C,QAAQ,KAAK,QAAb;EACE,KAAK,OACH,OAAO,GAAG,iBAAiB;EAC7B,KAAK,eACH,OAAO,GAAG,KAAK,KAAK;EACtB,SACE,OAAO,GAAG,KAAK,KAAK;CACxB;AACF;;AAGA,SAAgB,iBAAiB,MAA0C;CACzE,IAAI,CAAC,MACH,OAAO;EACL;EACA;EACA;CACF;CAEF,IAAI,KAAK,SAAS,UAAU;EAC1B,MAAM,QAAQ,KAAK;EACnB,IAAI,MAAM,SACR,OAAO,CACL,wBAAwB,MAAM,MAAM,cAAc,MAAM,UAAU,IAClE,uFACF;EAEF,OAAO;GACL,4BAA4B,MAAM;GAClC,eAAe,MAAM;GACrB,GAAI,MAAM,YAAY,CAAC,eAAe,MAAM,WAAW,IAAI,CAAC;GAC5D,eAAe,MAAM;EACvB;CACF;CACA,OAAO;EAC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ClD,OAAO;EACT;CACF;CACA,MAAM,SAAS,MAAM,wBAAwB;EAC3C;EACA,QAAQ,EAAE,aAAa,KAAK;EAC5B,GAAI,cAAc,EAAE,YAAY,IAAI,CAAC;CACvC,CAAC;CACD,MAAM,QAAQ,eAAe,OAAO,OAAO;CAC3C,MACE,OAAO,UACH,uBAAuB,QAAQ,cAAc,+BAA+B,GAAG,KAC/E,cACE,GAAG,MAAM,qCACT,GAAG,MAAM,0DACjB;CACA,KAAK,MAAM,QAAQ,OAAO,SAAS,MAAM,WAAW,MAAM;CAC1D,KAAK,MAAM,QAAQ,OAAO,SACxB,MAAM,mCAAmC,MAAM;CACjD,OAAO;AACT","debug_id":"cee9f7e8-d1fe-5e9e-b0c8-f66c5d03af19"}
@@ -1,9 +1,10 @@
1
1
  import { S as $strip, _ as ZodUnion, b as $loose, d as ZodOptional, g as ZodURL, i as ZodBoolean, l as ZodNumber, m as ZodString, n as input, o as ZodEnum, p as ZodRecord, r as ZodArray, s as ZodLiteral, t as external_d_exports, u as ZodObject, v as ZodUnknown, x as $strict, y as output } from "./external-M25AgDIE.mjs";
2
- import net from "node:net";
3
2
  import { EnvToken, TokenableSchema } from "@powerhousedao/shared/host-tokens";
4
3
  import "@powerhousedao/shared/connect/origin-placeholder";
4
+ import "@powerhousedao/shared/clis/owner-only";
5
+ import net from "node:net";
5
6
  import "@powerhousedao/shared/clis";
6
- //#region ../../packages/host-core/dist/control-channel-eqvyUF03.d.mts
7
+ //#region ../../packages/host-core/dist/control-channel-DVn4dvfQ.d.mts
7
8
  /** A run record's `extra.control`. */
8
9
  declare const controlRecordSchema: ZodObject<{
9
10
  protocol: ZodNumber;
@@ -12,7 +13,7 @@ declare const controlRecordSchema: ZodObject<{
12
13
  }, $strip>;
13
14
  type ControlRecord = output<typeof controlRecordSchema>;
14
15
  //#endregion
15
- //#region ../../packages/host-core/dist/compound-L62ALvYc.d.mts
16
+ //#region ../../packages/host-core/dist/compound-BLhEewO6.d.mts
16
17
  /** An installed package that supplies hosts: its name and its real folder,
17
18
  * which its host files and their module specifiers resolve from. */
18
19
  interface HostPackage {
@@ -257,4 +258,4 @@ declare global {
257
258
  //#endregion
258
259
  export { RunnerHandle as n, RunnerContext as t };
259
260
  export {};
260
- //# sourceMappingURL=index-Bs1PfL3W.d.mts.map
261
+ //# sourceMappingURL=index-aosqo7aM.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-aosqo7aM.d.mts","names":[],"sources":["../../../packages/host-core/dist/control-channel-DVn4dvfQ.d.mts","../../../packages/host-core/dist/compound-BLhEewO6.d.mts","../../../packages/host-core/dist/index.d.mts"],"mappings":";;;;;;;;cA+Ec,qBAAqB;EACjC,UAAU;EACV,SAAS;EACT,OAAO;GACN;KACE,gBAAgB,cAAe;;;;;UCjE1B;EACR;EACA;;cAykEY,mCAAmC;EAC/C,MAAM;EACN,QAAQ;IACN,QAAQ;IACR,aAAa,YAAc;IAC3B,MAAM,YAAc;IACpB,MAAM,YAAc;IACpB,SAAS,YAAc,SAAW,mBAAqB,WAAa;MAClE,QAAQ;MACR,SAAS,YAAc;MACvB,OAAO,YAAc,mBAAqB,iBAAmB,SAAW;MACxE,QAAQ,YAAc,UAAY,WAAa;OAC9C;KACF;EACH,UAAU,UAAY,WAAa;IACjC,MAAM;IACN,QAAQ,YAAc;MACpB,QAAQ,YAAc;MACtB,aAAa,YAAc,YAAc;MACzC,MAAM,YAAc,YAAc;MAClC,SAAS,YAAc,YAAc,SAAW,mBAAqB,WAAa;QAChF,QAAQ;QACR,SAAS,YAAc;QACvB,OAAO,YAAc,mBAAqB,iBAAmB,SAAW;QACxE,QAAQ,YAAc,UAAY,WAAa;SAC9C;MACH,MAAM,YAAc;OACnB;IACH,QAAQ,YAAc,cAAgB;IACtC,SAAS,YAAc;MACrB,UAAU,YAAc,UAAY,WAAa;QAC/C,MAAM;UACJ;UACA;UACA;;QAEF,SAAS,YAAc;UACrB,MAAM;YACJ;YACA;YACA;YACA;;UAEF,SAAS,YAAc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KACnB;EACH,QAAQ,YAAc;IACpB,YAAY,YAAc,SAAW;IACrC,eAAe,YAAc;IAC7B,iBAAiB,YAAc;KAC9B;GACF;UA2GO;;;EAGR;;;;EAIA,cAAc;;;EAGd;EACA,KAAK;;;EAGL;IACE;IACA;;;;;EAKF;;;;;;EAMA,mBAAmB;;;;EAInB,aAAa;;;UAGL;;EAER,oBAAoB;;;;EAIpB;;EAEA;;EAEA,UAAU;;;;;;;UAOF;;EAER;;EAEA;EACA;EACA;;EAEA;;EAEA,WAAW;;EAEX;EACA;;;;;;;;;;UA8MQ,aAAa,IAAI;EACzB,SAAS;;EAET,OAAO;;EAEP,YAAY;;;;;;QC/iEN;;;YAGI;;YAEA;;QA0CJ;YACI;IACR;MACE,MAAM,aAAe;MACrB,SAAS"}
@@ -1,8 +1,8 @@
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]="b5cb1a95-360f-5775-943b-344d627fa2c2")}catch(e){}}();
3
- import { t as readProjectSubgraphs } from "./subgraphs-7OYWwP-C.mjs";
4
- import { n as processStreams, r as runModelCommand } from "./run--de_-WAz.mjs";
5
- import { n as renderInspectionReport } from "./render-SVfj3m8A.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]="687714a8-f025-597f-969a-65d01d37ab69")}catch(e){}}();
3
+ import { t as readProjectSubgraphs } from "./subgraphs-Bm9NHTCn.mjs";
4
+ import { n as processStreams, r as runModelCommand } from "./run-sVzTTEUx.mjs";
5
+ import { n as renderInspectionReport } from "./render-CQdi685k.mjs";
6
6
  import { inspectProjectDefinitions, withSubgraphInspection } from "document-model/tooling";
7
7
  //#region src/services/model/inspect.ts
8
8
  /** `<documentType>@<version>`; a document type may itself contain `@`. */
@@ -48,5 +48,5 @@ async function runModelInspect(args, options = {}) {
48
48
  //#endregion
49
49
  export { runModelInspect };
50
50
 
51
- //# sourceMappingURL=inspect-CulIpVsF.mjs.map
52
- //# debugId=b5cb1a95-360f-5775-943b-344d627fa2c2
51
+ //# sourceMappingURL=inspect-BgKI8Fhd.mjs.map
52
+ //# debugId=687714a8-f025-597f-969a-65d01d37ab69
@@ -1 +1 @@
1
- {"version":3,"file":"inspect-CulIpVsF.mjs","sources":["../src/services/model/inspect.ts"],"sourcesContent":["import {\n inspectProjectDefinitions,\n withSubgraphInspection,\n} from \"document-model/tooling\";\nimport {\n type ModelRunOptions,\n processStreams,\n runModelCommand,\n} from \"./run.js\";\nimport { renderInspectionReport } from \"./render.js\";\nimport { readProjectSubgraphs } from \"./subgraphs.js\";\n\ntype Selection = { readonly documentType: string; readonly version: number };\n\n/** `<documentType>@<version>`; a document type may itself contain `@`. */\nfunction parseModelSelector(\n selector: string,\n):\n | { readonly ok: true; readonly selection: Selection }\n | { readonly ok: false; readonly message: string } {\n const at = selector.lastIndexOf(\"@\");\n const documentType = at === -1 ? \"\" : selector.slice(0, at);\n const version = at === -1 ? \"\" : selector.slice(at + 1);\n if (\n documentType === \"\" ||\n !/^[1-9][0-9]*$/.test(version) ||\n !Number.isSafeInteger(Number(version))\n ) {\n return {\n ok: false,\n message: `Expected <documentType>@<version> with a positive whole version, such as acme/invoice@1. Received ${JSON.stringify(selector)}.`,\n };\n }\n return { ok: true, selection: { documentType, version: Number(version) } };\n}\n\n/** `ph model inspect [<documentType>@<version>]`. Returns the exit code. */\nexport async function runModelInspect(\n args: { readonly selector?: string; readonly json: boolean },\n options: ModelRunOptions = {},\n): Promise<number> {\n let selection: Selection | undefined;\n if (args.selector !== undefined) {\n const parsed = parseModelSelector(args.selector);\n if (!parsed.ok) {\n (options.streams ?? processStreams).err(`${parsed.message}\\n`);\n return 2;\n }\n selection = parsed.selection;\n }\n return await runModelCommand(\n {\n name: \"ph model inspect\",\n json: args.json,\n read: async (project, modules) => {\n if (selection !== undefined) {\n return inspectProjectDefinitions(project, { selection });\n }\n const report = inspectProjectDefinitions(project);\n const subgraphs = await readProjectSubgraphs(project, modules);\n return subgraphs === undefined\n ? report\n : withSubgraphInspection(project, report, subgraphs.input);\n },\n render: renderInspectionReport,\n },\n options,\n );\n}\n"],"names":[],"mappings":";;;;;;;;AAeA,SAAS,mBACP,UAGmD;CACnD,MAAM,KAAK,SAAS,YAAY,GAAG;CACnC,MAAM,eAAe,OAAO,KAAK,KAAK,SAAS,MAAM,GAAG,EAAE;CAC1D,MAAM,UAAU,OAAO,KAAK,KAAK,SAAS,MAAM,KAAK,CAAC;CACtD,IACE,iBAAiB,MACjB,CAAC,gBAAgB,KAAK,OAAO,KAC7B,CAAC,OAAO,cAAc,OAAO,OAAO,CAAC,GAErC,OAAO;EACL,IAAI;EACJ,SAAS,qGAAqG,KAAK,UAAU,QAAQ,EAAE;CACzI;CAEF,OAAO;EAAE,IAAI;EAAM,WAAW;GAAE;GAAc,SAAS,OAAO,OAAO;EAAE;CAAE;AAC3E;;AAGA,eAAsB,gBACpB,MACA,UAA2B,CAAC,GACX;CACjB,IAAI;CACJ,IAAI,KAAK,aAAa,KAAA,GAAW;EAC/B,MAAM,SAAS,mBAAmB,KAAK,QAAQ;EAC/C,IAAI,CAAC,OAAO,IAAI;GACd,CAAC,QAAQ,WAAW,eAAA,CAAgB,IAAI,GAAG,OAAO,QAAQ,GAAG;GAC7D,OAAO;EACT;EACA,YAAY,OAAO;CACrB;CACA,OAAO,MAAM,gBACX;EACE,MAAM;EACN,MAAM,KAAK;EACX,MAAM,OAAO,SAAS,YAAY;GAChC,IAAI,cAAc,KAAA,GAChB,OAAO,0BAA0B,SAAS,EAAE,UAAU,CAAC;GAEzD,MAAM,SAAS,0BAA0B,OAAO;GAChD,MAAM,YAAY,MAAM,qBAAqB,SAAS,OAAO;GAC7D,OAAO,cAAc,KAAA,IACjB,SACA,uBAAuB,SAAS,QAAQ,UAAU,KAAK;EAC7D;EACA,QAAQ;CACV,GACA,OACF;AACF","debug_id":"b5cb1a95-360f-5775-943b-344d627fa2c2"}
1
+ {"version":3,"file":"inspect-BgKI8Fhd.mjs","sources":["../src/services/model/inspect.ts"],"sourcesContent":["import {\n inspectProjectDefinitions,\n withSubgraphInspection,\n} from \"document-model/tooling\";\nimport {\n type ModelRunOptions,\n processStreams,\n runModelCommand,\n} from \"./run.js\";\nimport { renderInspectionReport } from \"./render.js\";\nimport { readProjectSubgraphs } from \"./subgraphs.js\";\n\ntype Selection = { readonly documentType: string; readonly version: number };\n\n/** `<documentType>@<version>`; a document type may itself contain `@`. */\nfunction parseModelSelector(\n selector: string,\n):\n | { readonly ok: true; readonly selection: Selection }\n | { readonly ok: false; readonly message: string } {\n const at = selector.lastIndexOf(\"@\");\n const documentType = at === -1 ? \"\" : selector.slice(0, at);\n const version = at === -1 ? \"\" : selector.slice(at + 1);\n if (\n documentType === \"\" ||\n !/^[1-9][0-9]*$/.test(version) ||\n !Number.isSafeInteger(Number(version))\n ) {\n return {\n ok: false,\n message: `Expected <documentType>@<version> with a positive whole version, such as acme/invoice@1. Received ${JSON.stringify(selector)}.`,\n };\n }\n return { ok: true, selection: { documentType, version: Number(version) } };\n}\n\n/** `ph model inspect [<documentType>@<version>]`. Returns the exit code. */\nexport async function runModelInspect(\n args: { readonly selector?: string; readonly json: boolean },\n options: ModelRunOptions = {},\n): Promise<number> {\n let selection: Selection | undefined;\n if (args.selector !== undefined) {\n const parsed = parseModelSelector(args.selector);\n if (!parsed.ok) {\n (options.streams ?? processStreams).err(`${parsed.message}\\n`);\n return 2;\n }\n selection = parsed.selection;\n }\n return await runModelCommand(\n {\n name: \"ph model inspect\",\n json: args.json,\n read: async (project, modules) => {\n if (selection !== undefined) {\n return inspectProjectDefinitions(project, { selection });\n }\n const report = inspectProjectDefinitions(project);\n const subgraphs = await readProjectSubgraphs(project, modules);\n return subgraphs === undefined\n ? report\n : withSubgraphInspection(project, report, subgraphs.input);\n },\n render: renderInspectionReport,\n },\n options,\n );\n}\n"],"names":[],"mappings":";;;;;;;;AAeA,SAAS,mBACP,UAGmD;CACnD,MAAM,KAAK,SAAS,YAAY,GAAG;CACnC,MAAM,eAAe,OAAO,KAAK,KAAK,SAAS,MAAM,GAAG,EAAE;CAC1D,MAAM,UAAU,OAAO,KAAK,KAAK,SAAS,MAAM,KAAK,CAAC;CACtD,IACE,iBAAiB,MACjB,CAAC,gBAAgB,KAAK,OAAO,KAC7B,CAAC,OAAO,cAAc,OAAO,OAAO,CAAC,GAErC,OAAO;EACL,IAAI;EACJ,SAAS,qGAAqG,KAAK,UAAU,QAAQ,EAAE;CACzI;CAEF,OAAO;EAAE,IAAI;EAAM,WAAW;GAAE;GAAc,SAAS,OAAO,OAAO;EAAE;CAAE;AAC3E;;AAGA,eAAsB,gBACpB,MACA,UAA2B,CAAC,GACX;CACjB,IAAI;CACJ,IAAI,KAAK,aAAa,KAAA,GAAW;EAC/B,MAAM,SAAS,mBAAmB,KAAK,QAAQ;EAC/C,IAAI,CAAC,OAAO,IAAI;GACd,CAAC,QAAQ,WAAW,eAAA,CAAgB,IAAI,GAAG,OAAO,QAAQ,GAAG;GAC7D,OAAO;EACT;EACA,YAAY,OAAO;CACrB;CACA,OAAO,MAAM,gBACX;EACE,MAAM;EACN,MAAM,KAAK;EACX,MAAM,OAAO,SAAS,YAAY;GAChC,IAAI,cAAc,KAAA,GAChB,OAAO,0BAA0B,SAAS,EAAE,UAAU,CAAC;GAEzD,MAAM,SAAS,0BAA0B,OAAO;GAChD,MAAM,YAAY,MAAM,qBAAqB,SAAS,OAAO;GAC7D,OAAO,cAAc,KAAA,IACjB,SACA,uBAAuB,SAAS,QAAQ,UAAU,KAAK;EAC7D;EACA,QAAQ;CACV,GACA,OACF;AACF","debug_id":"687714a8-f025-597f-969a-65d01d37ab69"}
@@ -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]="872a0a4c-a394-510e-9f86-0be9f6fa07cd")}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]="ee6544ee-ad48-514d-a4bd-696d1fc3f922")}catch(e){}}();
3
3
  import { DEFAULT_SWITCHBOARD_PORT } from "@powerhousedao/shared/clis/constants";
4
4
  import { getConfig } from "@powerhousedao/shared/clis";
5
5
  import { KEYFRAME_ADMIN_OPERATIONS } from "@powerhousedao/reactor";
@@ -173,7 +173,7 @@ async function bearerToken(given) {
173
173
  const known = given ?? process.env.PH_ACCESS_TOKEN;
174
174
  if (known) return known;
175
175
  const { generateAccessToken } = await import("@renown/sdk/node");
176
- const { getRenown } = await import("./auth-CNhbN5UM.mjs");
176
+ const { getRenown } = await import("./auth-5bqHASGL.mjs");
177
177
  const { token } = await generateAccessToken(await getRenown(), { expiresIn: 3600 });
178
178
  return token;
179
179
  }
@@ -197,5 +197,5 @@ async function runKeyframesCommand(args) {
197
197
  //#endregion
198
198
  export { runKeyframesCommand };
199
199
 
200
- //# sourceMappingURL=keyframes-bFo9iDhT.mjs.map
201
- //# debugId=872a0a4c-a394-510e-9f86-0be9f6fa07cd
200
+ //# sourceMappingURL=keyframes-BkeORfEu.mjs.map
201
+ //# debugId=ee6544ee-ad48-514d-a4bd-696d1fc3f922
@@ -1 +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,SA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AAK;CACd;AACF;AAEA,SAAS,oBAA4B;CAEnC,OAAO,oBADM,UAAU,CAAC,CAAC,SAAS,QAAQ,yBACV;AAClC;AAEA,eAAe,YAAY,OAA4C;CACrE,MAAM,QAAQ,SAAS,QAAQ,IAAI;CACnC,IAAI,OAAO,OAAO;CAClB,MAAM,EAAE,wBAAwB,MAAM,OAAO;CAC7C,MAAM,EAAE,cAAc,MAAM,OAAO;CACnC,MAAM,EAAE,UAAU,MAAM,oBAAoB,MAAM,UAAU,GAAG,EAC7D,WAAW,KACb,CAAC;CACD,OAAO;AACT;;AAGA,eAAsB,oBACpB,MACiB;CACjB,MAAM,SAA0B;EAC9B,MAAM,SAAS,QAAQ,IAAI,IAAI;EAC/B,MAAM,SAAS,QAAQ,MAAM,IAAI;CACnC;CACA,IAAI;EAKF,OAAO,MAAM,uBAAuB,MAAM;GACxC,SALc,iBACd,kBAAkB,KAAK,OAAO,kBAAkB,CAAC,GACjD,MAAM,YAAY,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
+ {"version":3,"file":"keyframes-BkeORfEu.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,KA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oBAAoB,MAAM,UAAU,GAAG,EAC7D,WAAW,KACb,CAAC;CACD,OAAO;AACT;;AAGA,eAAsB,oBACpB,MACiB;CACjB,MAAM,SAA0B;EAC9B,MAAM,SAAS,QAAQ,IAAI,IAAI;EAC/B,MAAM,SAAS,QAAQ,MAAM,IAAI;CACnC;CACA,IAAI;EAKF,OAAO,MAAM,uBAAuB,MAAM;GACxC,SALc,iBACd,kBAAkB,KAAK,OAAO,kBAAkB,CAAC,GACjD,MAAM,YAAY,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":"ee6544ee-ad48-514d-a4bd-696d1fc3f922"}
@@ -1,11 +1,12 @@
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]="5b7c1d09-4ebb-59d8-a6ae-ec4a37dc37b6")}catch(e){}}();
3
- import { t as getVersion } from "./get-version-DAYhm6MX.mjs";
4
- import { o as readVetraRuntime } from "./vetra-instance-CLUzbtbh.mjs";
5
- import { a as restartVetra, n as currentPhCliRunVetraCommand, r as ensureVetra, t as VetraStartError } from "./vetra-launcher-Dq0tWyNW.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]="4842d577-7fb4-5bf9-8853-ddeba294b81f")}catch(e){}}();
3
+ import { t as getVersion } from "./get-version-CTP__ORu.mjs";
4
+ import { a as restartVetra, n as currentPhCliRunVetraCommand, r as ensureVetra, t as VetraStartError } from "./vetra-launcher-6NKfi6Au.mjs";
5
+ import { i as readVetraRuntime } from "./vetra-runtime-Bk6CW-BE.mjs";
6
6
  import { resolveSwitchboardPortDefault } from "@powerhousedao/shared/clis/args";
7
7
  import fs from "node:fs";
8
8
  import path from "node:path";
9
+ import { identityDataDir } from "@powerhousedao/shared/clis/identity";
9
10
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
10
11
  import { StreamableHTTPClientTransport, StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
11
12
  import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
@@ -61,7 +62,7 @@ function isStaleConnection(error) {
61
62
  }
62
63
  const restartVetraTool = {
63
64
  name: "restartVetra",
64
- description: "Restart this project's Vetra (its Switchboard and Studio) and wait until it is ready. Use it after a change Vetra reads only at startup, such as the reactor or packages settings in powerhouse.config.json; Studio restarts by itself for connect.* changes. Returns the new Connect, Switchboard and MCP URLs.",
65
+ description: "Restart this project's dev stack (its Switchboard and Connect, what `ph dev` runs) and wait until it is ready. Use it after a change the stack reads only at startup, such as the reactor or packages settings in powerhouse.config.json; Connect restarts by itself for connect.* changes. Returns the new Connect, Switchboard and MCP URLs.",
65
66
  inputSchema: {
66
67
  type: "object",
67
68
  properties: {}
@@ -98,6 +99,8 @@ var Upstream = class {
98
99
  #client;
99
100
  /** The Vetra the client talks to; another pid in the record means it restarted. */
100
101
  #pid;
102
+ /** That Vetra's record, for its Switchboard's GraphQL endpoint. */
103
+ #record;
101
104
  /** The calls waiting on the connection, told how Vetra's start goes. */
102
105
  #waiting = /* @__PURE__ */ new Set();
103
106
  constructor(projectDir, options) {
@@ -114,6 +117,11 @@ var Upstream = class {
114
117
  });
115
118
  return this.#waitWith(this.#client, onProgress);
116
119
  }
120
+ /** The running Vetra's Switchboard GraphQL endpoint, starting Vetra when it is down. */
121
+ async switchboard(onProgress) {
122
+ await this.get(onProgress);
123
+ return vetraUrls(this.#record).switchboardUrl;
124
+ }
117
125
  async #waitWith(task, onProgress) {
118
126
  if (onProgress) this.#waiting.add(onProgress);
119
127
  try {
@@ -156,7 +164,7 @@ var Upstream = class {
156
164
  projectDir,
157
165
  projectName: name,
158
166
  switchboardPort: resolveSwitchboardPortDefault(),
159
- command: this.options.vetraCommand ?? currentPhCliRunVetraCommand(),
167
+ command: this.options.vetraCommand ?? currentPhCliRunVetraCommand(projectDir),
160
168
  timeoutMs: this.options.startTimeoutSeconds * 1e3,
161
169
  onProgress: this.#report
162
170
  });
@@ -167,6 +175,7 @@ var Upstream = class {
167
175
  });
168
176
  await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl)));
169
177
  this.#pid = record.pid;
178
+ this.#record = record;
170
179
  console.error(`[ph mcp] forwarding tool calls to ${mcpUrl}`);
171
180
  return client;
172
181
  }
@@ -188,6 +197,131 @@ async function forwardToolCall(upstream, params, signal, onProgress) {
188
197
  }
189
198
  }
190
199
  }
200
+ /** The tools that write: they run here, signed and borne as the MCP client's session. */
201
+ const SIGNED_TOOLS = /* @__PURE__ */ new Set([
202
+ "createDocument",
203
+ "addActions",
204
+ "deleteDocument"
205
+ ]);
206
+ /** What an MCP client's session is called, and its credential signs. */
207
+ function mcpSessionLabel(clientName) {
208
+ return `mcp ${clientName?.trim() || "client"}`;
209
+ }
210
+ /** How long a Renown approval of a session is waited for. */
211
+ const APPROVAL_WAIT_MS = 6e5;
212
+ /**
213
+ * The writing tools, run in this process over the project's Switchboard,
214
+ * every action signed and every request borne as the MCP client's own
215
+ * session (`mcp <client>`), kept in the project's data folder with its
216
+ * credential's record: the pseudonym's, issued at the first write, or one a
217
+ * Renown login approves once at Renown's console. A call that needs a model
218
+ * this process does not hold, before it wrote anything, goes to the host's
219
+ * `/mcp` instead, which signs its writes itself.
220
+ */
221
+ var SignedTools = class {
222
+ projectDir;
223
+ #models;
224
+ /** The console approvals waited for, by session label. */
225
+ #approvals = /* @__PURE__ */ new Map();
226
+ constructor(projectDir) {
227
+ this.projectDir = projectDir;
228
+ }
229
+ #localModels() {
230
+ this.#models ??= import("@powerhousedao/reactor-mcp/remote").then(({ localDocumentModels }) => localDocumentModels(this.projectDir, { onError: (error) => console.error(`[ph mcp] the project's document models did not load: ${error instanceof Error ? error.message : String(error)}`) }));
231
+ return this.#models;
232
+ }
233
+ async call(params, label, graphqlUrl, signal) {
234
+ const identity = await import("@renown/sdk/identity");
235
+ const dataDir = identityDataDir(this.projectDir);
236
+ let session;
237
+ try {
238
+ session = await identity.openSession({
239
+ dataDir,
240
+ label,
241
+ place: "data-folder",
242
+ interactive: false,
243
+ target: { dataDir },
244
+ reissueWithdrawn: false
245
+ });
246
+ } catch (error) {
247
+ if (error instanceof identity.SessionApprovalRequiredError) return { result: toolError(this.#approve(identity, label, dataDir)) };
248
+ throw error;
249
+ }
250
+ const [{ createRemoteServer }, { GraphQLReactorClient }, models] = await Promise.all([
251
+ import("@powerhousedao/reactor-mcp/remote"),
252
+ import("@powerhousedao/reactor-browser/graphql-client"),
253
+ this.#localModels()
254
+ ]);
255
+ const client = new GraphQLReactorClient({
256
+ url: graphqlUrl,
257
+ documentModels: () => models.current(),
258
+ signer: session.actionSigner,
259
+ tokenProvider: () => session.bearer(),
260
+ realtime: false
261
+ });
262
+ const seen = {
263
+ missing: false,
264
+ wrote: false
265
+ };
266
+ const server = createRemoteServer({
267
+ client,
268
+ documentModels: () => models.current(),
269
+ onMissingModel: () => {
270
+ seen.missing = true;
271
+ },
272
+ onWrite: () => {
273
+ seen.wrote = true;
274
+ }
275
+ });
276
+ const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
277
+ const local = new Client({
278
+ name: "ph-mcp",
279
+ version: getVersion()
280
+ });
281
+ try {
282
+ await server.connect(serverSide);
283
+ await local.connect(clientSide);
284
+ const result = await local.request({
285
+ method: "tools/call",
286
+ params
287
+ }, CallToolResultSchema, {
288
+ signal,
289
+ timeout: CALL_TIMEOUT_MS
290
+ });
291
+ if (result.isError && seen.missing && !seen.wrote) return { forward: true };
292
+ return { result };
293
+ } finally {
294
+ client.dispose();
295
+ await local.close().catch(() => {});
296
+ await server.close().catch(() => {});
297
+ }
298
+ }
299
+ /** Starts, once per session, the approval a Renown login gives at the console. */
300
+ #approve(identity, label, dataDir) {
301
+ const waiting = this.#approvals.get(label);
302
+ if (waiting) return waiting;
303
+ const approval = identity.startSessionApproval({
304
+ dataDir,
305
+ label
306
+ });
307
+ const message = `This MCP client acts for your Renown login, and its session "${label}" needs your approval once: open ${approval.url}, approve it with your wallet, then call the tool again.`;
308
+ this.#approvals.set(label, message);
309
+ import("@renown/sdk/node").then(({ openBrowser }) => openBrowser(approval.url)).catch(() => {});
310
+ identity.pollSessionApproval({
311
+ approval,
312
+ timeoutMs: APPROVAL_WAIT_MS,
313
+ target: { dataDir }
314
+ }).then((outcome) => {
315
+ if (outcome.status === "ready") console.error(`[ph mcp] ${label} approved for ${outcome.address}`);
316
+ }).catch((error) => console.error(`[ph mcp] the approval of ${label} failed: ${error instanceof Error ? error.message : String(error)}`)).finally(() => this.#approvals.delete(label));
317
+ return message;
318
+ }
319
+ async close() {
320
+ const models = this.#models;
321
+ this.#models = void 0;
322
+ await (await models)?.close();
323
+ }
324
+ };
191
325
  /** `ph mcp`: tools listed by in-process reactor-mcp, calls forwarded to Vetra (started on first call). */
192
326
  async function startMcpLauncher(options) {
193
327
  console.log = console.error;
@@ -196,6 +330,7 @@ async function startMcpLauncher(options) {
196
330
  if (projectDir) process.chdir(projectDir);
197
331
  const local = await connectLocalReactorMcp();
198
332
  const upstream = new Upstream(projectDir, options);
333
+ const signed = projectDir ? new SignedTools(projectDir) : void 0;
199
334
  const server = new Server(local.getServerVersion() ?? {
200
335
  name: "reactor-mcp-server",
201
336
  version: ""
@@ -244,6 +379,10 @@ async function startMcpLauncher(options) {
244
379
  structuredContent: urls
245
380
  };
246
381
  }
382
+ if (signed && SIGNED_TOOLS.has(request.params.name)) {
383
+ const answer = await signed.call(request.params, mcpSessionLabel(server.getClientVersion()?.name), await upstream.switchboard(onProgress), extra.signal);
384
+ if ("result" in answer) return answer.result;
385
+ }
247
386
  return await forwardToolCall(upstream, request.params, extra.signal, onProgress);
248
387
  } catch (error) {
249
388
  if (error instanceof McpError) throw error;
@@ -252,12 +391,15 @@ async function startMcpLauncher(options) {
252
391
  }
253
392
  });
254
393
  const transport = new StdioServerTransport();
255
- transport.onclose = () => process.exit(0);
256
- process.stdin.once("end", () => process.exit(0));
394
+ const exit = () => {
395
+ (signed?.close() ?? Promise.resolve()).catch(() => {}).finally(() => process.exit(0));
396
+ };
397
+ transport.onclose = exit;
398
+ process.stdin.once("end", exit);
257
399
  await server.connect(transport);
258
400
  }
259
401
  //#endregion
260
402
  export { startMcpLauncher };
261
403
 
262
- //# sourceMappingURL=mcp-rtMGg307.mjs.map
263
- //# debugId=5b7c1d09-4ebb-59d8-a6ae-ec4a37dc37b6
404
+ //# sourceMappingURL=mcp-gcG7SW9L.mjs.map
405
+ //# debugId=4842d577-7fb4-5bf9-8853-ddeba294b81f