@powerhousedao/ph-cli 6.3.0-dev.11 → 6.3.0-dev.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/build-CXw4I2Wu.mjs +4 -0
- package/dist/{build-C9gXPccv.mjs → build-DpcVpv1e.mjs} +6 -6
- package/dist/{build-C9gXPccv.mjs.map → build-DpcVpv1e.mjs.map} +1 -1
- package/dist/{check-CBZ44SDf.mjs → check-BG_Ouby3.mjs} +7 -7
- package/dist/check-BG_Ouby3.mjs.map +1 -0
- package/dist/{check-B8oqVMg7.mjs → check-DZpL_1W5.mjs} +4 -4
- package/dist/{check-B8oqVMg7.mjs.map → check-DZpL_1W5.mjs.map} +1 -1
- package/dist/{check-Bdvm8hz0.mjs → check-Dg8sy76q.mjs} +3 -3
- package/dist/{classic-warnings-BR0S6lr5.mjs → classic-warnings-Hfz6cEEa.mjs} +4 -4
- package/dist/{classic-warnings-BR0S6lr5.mjs.map → classic-warnings-Hfz6cEEa.mjs.map} +1 -1
- package/dist/{cli-connect-override-D22yFWlC.mjs → cli-connect-override-BRU7ykux.mjs} +4 -4
- package/dist/{cli-connect-override-D22yFWlC.mjs.map → cli-connect-override-BRU7ykux.mjs.map} +1 -1
- package/dist/cli.mjs +5 -5
- package/dist/{compound-DKi56SSx-CXQHhS6t.mjs → compound-DKi56SSx-DAr69gXP.mjs} +63 -4
- package/dist/{compound-DKi56SSx-CXQHhS6t.mjs.map → compound-DKi56SSx-DAr69gXP.mjs.map} +1 -1
- package/dist/{connect-build-BqRWG3tZ.mjs → connect-build-XCiuZ06m.mjs} +5 -5
- package/dist/{connect-build-BqRWG3tZ.mjs.map → connect-build-XCiuZ06m.mjs.map} +1 -1
- package/dist/{connect-config-CVU4xhti.mjs → connect-config-sT4vaYEZ.mjs} +4 -4
- package/dist/{connect-config-CVU4xhti.mjs.map → connect-config-sT4vaYEZ.mjs.map} +1 -1
- package/dist/{connect-studio-D58ByAAn.mjs → connect-studio-_3kPJnXx.mjs} +3 -3
- package/dist/connect-studio-b53V1sw8.mjs +182 -0
- package/dist/connect-studio-b53V1sw8.mjs.map +1 -0
- package/dist/definitions-worker.mjs +4 -4
- package/dist/definitions-worker.mjs.map +1 -1
- package/dist/{dist-DXcB8fAF.mjs → dist-CuwtgEmh.mjs} +4 -4
- package/dist/{dist-DXcB8fAF.mjs.map → dist-CuwtgEmh.mjs.map} +1 -1
- package/dist/{explain-8OEXF2Dy.mjs → explain-BrZthZF6.mjs} +5 -5
- package/dist/{explain-8OEXF2Dy.mjs.map → explain-BrZthZF6.mjs.map} +1 -1
- package/dist/{export-DqbcbFU5.mjs → export-BvdnQIps.mjs} +4 -4
- package/dist/{export-DqbcbFU5.mjs.map → export-BvdnQIps.mjs.map} +1 -1
- package/dist/{generate-all-0YOnlZM0.mjs → generate-all-WJdSqrjR.mjs} +4 -4
- package/dist/{generate-all-0YOnlZM0.mjs.map → generate-all-WJdSqrjR.mjs.map} +1 -1
- package/dist/{generate-document-model-BiD6ovXc.mjs → generate-document-model-DjV0F1Y5.mjs} +7 -9
- package/dist/generate-document-model-DjV0F1Y5.mjs.map +1 -0
- package/dist/{generate-subgraph-DJZCr0Tk.mjs → generate-subgraph-BLPP_h4D.mjs} +11 -23
- package/dist/generate-subgraph-BLPP_h4D.mjs.map +1 -0
- package/dist/{get-version-DQ6JaxAS.mjs → get-version-CIqOBtIW.mjs} +4 -4
- package/dist/{get-version-DQ6JaxAS.mjs.map → get-version-CIqOBtIW.mjs.map} +1 -1
- package/dist/{inspect-CulIpVsF.mjs → inspect-BgKI8Fhd.mjs} +6 -6
- package/dist/{inspect-CulIpVsF.mjs.map → inspect-BgKI8Fhd.mjs.map} +1 -1
- package/dist/{mcp-DTGhGK20.mjs → mcp-PBjhPGrv.mjs} +6 -6
- package/dist/{mcp-DTGhGK20.mjs.map → mcp-PBjhPGrv.mjs.map} +1 -1
- package/dist/{migrate-document-models-BsHvClbh.mjs → migrate-document-models-CGt4nfp5.mjs} +5 -6
- package/dist/migrate-document-models-CGt4nfp5.mjs.map +1 -0
- package/dist/{migrate-B9Im3uim.mjs → migrate-rzcmLt3M.mjs} +4 -4
- package/dist/{migrate-B9Im3uim.mjs.map → migrate-rzcmLt3M.mjs.map} +1 -1
- package/dist/migrate-subgraphs-4kM3eLP5.mjs +4 -0
- package/dist/{migrate-subgraphs-CGIPAnQB.mjs → migrate-subgraphs-CEZc5MyM.mjs} +6 -7
- package/dist/migrate-subgraphs-CEZc5MyM.mjs.map +1 -0
- package/dist/{ph-cli-commands-Bea3C3iI.mjs → ph-cli-commands-CVBzs-4X.mjs} +37 -42
- package/dist/ph-cli-commands-CVBzs-4X.mjs.map +1 -0
- package/dist/ph-cli-commands-DWbyQdvG.mjs +4 -0
- package/dist/render-BQE20Cnd.mjs +4 -0
- package/dist/{render-SVfj3m8A.mjs → render-CQdi685k.mjs} +6 -6
- package/dist/render-CQdi685k.mjs.map +1 -0
- package/dist/{run-LRGy7zGo.mjs → run-C6Vha5VN.mjs} +3 -3
- package/dist/{run--de_-WAz.mjs → run-sVzTTEUx.mjs} +5 -36
- package/dist/run-sVzTTEUx.mjs.map +1 -0
- package/dist/{run-sugar-DpznOP1e.mjs → run-sugar-BqRKMdsc.mjs} +4 -4
- package/dist/{run-sugar-DpznOP1e.mjs.map → run-sugar-BqRKMdsc.mjs.map} +1 -1
- package/dist/runners/connect.d.mts +13 -2
- package/dist/runners/connect.d.mts.map +1 -1
- package/dist/runners/connect.mjs +13 -7
- package/dist/runners/connect.mjs.map +1 -1
- package/dist/runners/switchboard.mjs +3 -3
- package/dist/{subgraphs-7OYWwP-C.mjs → subgraphs-Bm9NHTCn.mjs} +5 -38
- package/dist/subgraphs-Bm9NHTCn.mjs.map +1 -0
- package/dist/{verify-BRofKAkt.mjs → verify-CbhHneDD.mjs} +4 -4
- package/dist/{verify-BRofKAkt.mjs.map → verify-CbhHneDD.mjs.map} +1 -1
- package/dist/{vetra-CVNZ46pK.mjs → vetra-DR1C6-wd.mjs} +16 -9
- package/dist/{vetra-CVNZ46pK.mjs.map → vetra-DR1C6-wd.mjs.map} +1 -1
- package/dist/{vetra-host-ChTpJiBJ.mjs → vetra-host-CHcHhb97.mjs} +6 -5
- package/dist/{vetra-host-ChTpJiBJ.mjs.map → vetra-host-CHcHhb97.mjs.map} +1 -1
- package/dist/vetra-instance-B94ivpPZ.mjs +33 -0
- package/dist/vetra-instance-B94ivpPZ.mjs.map +1 -0
- package/dist/{vetra-launch-qi10Unax.mjs → vetra-launch-sLUPOntK.mjs} +7 -6
- package/dist/{vetra-launch-qi10Unax.mjs.map → vetra-launch-sLUPOntK.mjs.map} +1 -1
- package/dist/{vetra-instance-CzhYIjxL.mjs → vetra-runtime-kxkKcxOw.mjs} +4 -30
- package/dist/vetra-runtime-kxkKcxOw.mjs.map +1 -0
- package/package.json +17 -16
- package/dist/build-BxoiFvnE.mjs +0 -4
- package/dist/check-CBZ44SDf.mjs.map +0 -1
- package/dist/connect-studio-BnfhpIv8.mjs +0 -97
- package/dist/connect-studio-BnfhpIv8.mjs.map +0 -1
- package/dist/generate-document-model-BiD6ovXc.mjs.map +0 -1
- package/dist/generate-subgraph-DJZCr0Tk.mjs.map +0 -1
- package/dist/migrate-document-models-BsHvClbh.mjs.map +0 -1
- package/dist/migrate-subgraphs-CGIPAnQB.mjs.map +0 -1
- package/dist/migrate-subgraphs-DrTVwm8g.mjs +0 -4
- package/dist/ph-cli-commands-Bea3C3iI.mjs.map +0 -1
- package/dist/ph-cli-commands-iEIgXAIf.mjs +0 -4
- package/dist/render-3M3DwFzO.mjs +0 -4
- package/dist/render-SVfj3m8A.mjs.map +0 -1
- package/dist/run--de_-WAz.mjs.map +0 -1
- package/dist/subgraphs-7OYWwP-C.mjs.map +0 -1
- package/dist/vetra-instance-CzhYIjxL.mjs.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
|
|
2
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]="0de87e24-afd6-5e67-bda7-2d34eb9241c2")}catch(e){}}();
|
|
3
|
-
import {
|
|
4
|
-
import { s as projectDriveId, u as resolveDriveDeclaration } from "../dist-
|
|
3
|
+
import { M as normalizePluginEntry, g as entryActiveForVerb, j as normalizePluginEntries } from "../compound-DKi56SSx-DAr69gXP.mjs";
|
|
4
|
+
import { s as projectDriveId, u as resolveDriveDeclaration } from "../dist-CuwtgEmh.mjs";
|
|
5
5
|
import { DEFAULT_SWITCHBOARD_PORT } from "@powerhousedao/shared/clis/constants";
|
|
6
6
|
import { VETRA_PROCESSOR_CONFIG_KEY } from "@powerhousedao/config";
|
|
7
7
|
import { dev as dev$1, run as run$1 } from "@powerhousedao/ph-run/runners/switchboard";
|
|
@@ -19,7 +19,7 @@ const verbs = [
|
|
|
19
19
|
/** Build the project's reactor package (the SAME service as `ph build`) — what
|
|
20
20
|
* this switchboard serves. Starts no server; orthogonal to run/serve/dev. */
|
|
21
21
|
async function build(host, _ctx) {
|
|
22
|
-
const { runBuild } = await import("../build-
|
|
22
|
+
const { runBuild } = await import("../build-CXw4I2Wu.mjs");
|
|
23
23
|
const { classicBuildArgs } = await import("../classic-args-mH_DVsgC.mjs");
|
|
24
24
|
const classic = await classicBuildArgs();
|
|
25
25
|
await runBuild({
|
|
@@ -1,44 +1,11 @@
|
|
|
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]="
|
|
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]="3f8fce55-4f50-526a-9192-6274d6131949")}catch(e){}}();
|
|
3
3
|
import { r as scanSubgraphs, t as SUBGRAPHS_ENTRY } from "./subgraph-gate-BJ2PWXVY.mjs";
|
|
4
|
-
import {
|
|
4
|
+
import { statSync } from "node:fs";
|
|
5
5
|
import { join } from "node:path";
|
|
6
|
-
import { readSubgraphDefinitions, subgraphCheckInput } from "document-model/tooling";
|
|
6
|
+
import { readSubgraphDefinitions, schemaFirstSource, subgraphCheckInput } from "document-model/tooling";
|
|
7
7
|
import { projectSubgraphGraphQL } from "document-model";
|
|
8
8
|
import { parse, print } from "graphql";
|
|
9
|
-
//#region src/services/model/schema-first/sdl-sources.ts
|
|
10
|
-
const SDL_FILES = [
|
|
11
|
-
["schema.graphql", "graphql"],
|
|
12
|
-
["schema.ts", "typescript"],
|
|
13
|
-
["index.ts", "typescript"]
|
|
14
|
-
];
|
|
15
|
-
const LITERAL_NAME = /\bname(?:\s*:\s*string)?\s*=\s*["'`]([^"'`$]+)["'`]/;
|
|
16
|
-
function readText(path) {
|
|
17
|
-
if (!(statSync(path, { throwIfNoEntry: false })?.isFile() ?? false)) return null;
|
|
18
|
-
return readFileSync(path, "utf8");
|
|
19
|
-
}
|
|
20
|
-
function schemaFirstSource(projectRoot, dir) {
|
|
21
|
-
const unit = `./subgraphs/${dir}/`;
|
|
22
|
-
const name = readText(join(projectRoot, "subgraphs", dir, "index.ts"))?.match(LITERAL_NAME)?.[1] ?? null;
|
|
23
|
-
for (const [file, language] of SDL_FILES) {
|
|
24
|
-
const text = readText(join(projectRoot, "subgraphs", dir, file));
|
|
25
|
-
if (text !== null) return {
|
|
26
|
-
unit,
|
|
27
|
-
name,
|
|
28
|
-
source: { specifier: `${unit}${file}` },
|
|
29
|
-
language,
|
|
30
|
-
text
|
|
31
|
-
};
|
|
32
|
-
}
|
|
33
|
-
return {
|
|
34
|
-
unit,
|
|
35
|
-
name,
|
|
36
|
-
source: { specifier: `${unit}index.ts` },
|
|
37
|
-
language: "typescript",
|
|
38
|
-
text: null
|
|
39
|
-
};
|
|
40
|
-
}
|
|
41
|
-
//#endregion
|
|
42
9
|
//#region src/services/model/subgraphs.ts
|
|
43
10
|
const SCALARS_ENTRY = "./scalars/index.ts";
|
|
44
11
|
/** A module that hangs on a top-level await must not hang `ph model`. */
|
|
@@ -130,5 +97,5 @@ async function readProjectSubgraphs(project, modules, timeoutMs = IMPORT_TIMEOUT
|
|
|
130
97
|
//#endregion
|
|
131
98
|
export { readProjectSubgraphs as t };
|
|
132
99
|
|
|
133
|
-
//# sourceMappingURL=subgraphs-
|
|
134
|
-
//# debugId=
|
|
100
|
+
//# sourceMappingURL=subgraphs-Bm9NHTCn.mjs.map
|
|
101
|
+
//# debugId=3f8fce55-4f50-526a-9192-6274d6131949
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"subgraphs-Bm9NHTCn.mjs","sources":["../src/services/model/subgraphs.ts"],"sourcesContent":["import { projectSubgraphGraphQL } from \"document-model\";\nimport { type DocumentNode, parse, print } from \"graphql\";\nimport {\n type ProjectDefinitions,\n readSubgraphDefinitions,\n schemaFirstSource,\n subgraphCheckInput,\n type SubgraphCheckInput,\n type SubgraphDefinitions,\n type SubgraphHostConflict,\n type SubgraphImportFailure,\n type SubgraphInventoryEntry,\n} from \"document-model/tooling\";\nimport type { ProjectModules } from \"@powerhousedao/codegen/utils\";\nimport { statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { scanSubgraphs, SUBGRAPHS_ENTRY } from \"./subgraph-gate.js\";\n\nconst SCALARS_ENTRY = \"./scalars/index.ts\";\n\n/** A module that hangs on a top-level await must not hang `ph model`. */\nconst IMPORT_TIMEOUT_MS = 60_000;\n\nexport type ProjectSubgraphs = {\n readonly input: SubgraphCheckInput;\n readonly inventory: readonly SubgraphInventoryEntry[];\n};\n\ntype Imported =\n | { readonly ok: true; readonly namespace: object }\n | { readonly ok: false; readonly failure: SubgraphImportFailure };\n\nasync function importModule(\n modules: ProjectModules,\n specifier: `./${string}`,\n packageRoot: string,\n timeoutMs: number,\n): Promise<Imported> {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () =>\n reject(\n new Error(\n `it did not finish loading within ${timeoutMs / 1000} seconds`,\n ),\n ),\n timeoutMs,\n );\n timer.unref();\n });\n try {\n return {\n ok: true,\n namespace: await Promise.race([modules.importModule(specifier), timeout]),\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n ok: false,\n failure: { specifier, reason: message.replaceAll(packageRoot, \".\") },\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** The host's admission of the code-first subgraphs, replayed against its built-in subgraphs and the package's document models. */\nasync function replayHostAdmission(\n { subgraphs }: SubgraphDefinitions,\n artifacts: ProjectDefinitions[\"artifacts\"],\n): Promise<readonly SubgraphHostConflict[]> {\n if (subgraphs.length === 0) return [];\n const models = new Map(\n artifacts.map(({ documentType, documentModel }) => [\n documentType,\n documentModel.global,\n ]),\n );\n const { findPackageSubgraphConflicts } =\n await import(\"@powerhousedao/reactor-api/subgraph-types\");\n const { conflicts } = await findPackageSubgraphConflicts(\n subgraphs.map(({ name, definition }) => ({\n name,\n // The host serves the printed projection, parsed again.\n typeDefs: parse(\n print(projectSubgraphGraphQL(definition) as unknown as DocumentNode),\n ),\n })),\n [...models.values()],\n );\n return Array.from(conflicts).flatMap(\n ([subgraph, { nameHeldBy, claims }]): SubgraphHostConflict[] =>\n nameHeldBy === \"package\"\n ? []\n : [\n {\n subgraph,\n ...(nameHeldBy !== undefined && { nameHeldBy }),\n claims,\n },\n ],\n );\n}\n\nconst usesPackageScalars = ({ subgraphs }: SubgraphDefinitions) =>\n subgraphs.some(({ definition }) =>\n definition.scalars.some(({ implementation }) =>\n implementation.startsWith(\"package#\"),\n ),\n );\n\n/**\n * `undefined` when the project has no code-first subgraph: then nothing here\n * imports a module, and projects without one keep the reports they had. A\n * module that fails or outlives `timeoutMs` becomes a diagnostic.\n */\nexport async function readProjectSubgraphs(\n project: Pick<ProjectDefinitions, \"packageRoot\" | \"artifacts\">,\n modules: ProjectModules,\n timeoutMs: number = IMPORT_TIMEOUT_MS,\n): Promise<ProjectSubgraphs | undefined> {\n const root = project.packageRoot;\n const styles = scanSubgraphs(root);\n if (!styles.hasCodeFirst) return undefined;\n const schemaFirst = styles.schemaFirstUnits.map((dir) =>\n schemaFirstSource(root, dir),\n );\n const subgraphs = await importModule(\n modules,\n SUBGRAPHS_ENTRY,\n root,\n timeoutMs,\n );\n if (!subgraphs.ok) {\n return subgraphCheckInput({\n definitions: { subgraphs: [], diagnostics: [] },\n schemaFirst,\n importFailures: [subgraphs.failure],\n });\n }\n const definitions = readSubgraphDefinitions(subgraphs.namespace, {\n specifier: SUBGRAPHS_ENTRY,\n });\n const hostConflicts = await replayHostAdmission(\n definitions,\n project.artifacts,\n );\n if (!usesPackageScalars(definitions)) {\n return subgraphCheckInput({ definitions, schemaFirst, hostConflicts });\n }\n if (\n !(\n statSync(join(root, SCALARS_ENTRY), {\n throwIfNoEntry: false,\n })?.isFile() ?? false\n )\n ) {\n return subgraphCheckInput({\n definitions,\n schemaFirst,\n hostConflicts,\n scalars: null,\n });\n }\n const scalars = await importModule(modules, SCALARS_ENTRY, root, timeoutMs);\n return subgraphCheckInput(\n scalars.ok\n ? { definitions, schemaFirst, hostConflicts, scalars: scalars.namespace }\n : {\n definitions,\n schemaFirst,\n hostConflicts,\n importFailures: [scalars.failure],\n },\n );\n}\n"],"names":[],"mappings":";;;;;;;;;AAkBA,MAAM,gBAAgB;;AAGtB,MAAM,oBAAoB;AAW1B,eAAe,aACb,SACA,WACA,aACA,WACmB;CACnB,IAAI;CACJ,MAAM,UAAU,IAAI,SAAgB,GAAG,WAAW;EAChD,QAAQ,iBAEJ,uBACE,IAAI,MACF,oCAAoC,YAAY,IAAK,SACvD,CACF,GACF,SACF;EACA,MAAM,MAAM;CACd,CAAC;CACD,IAAI;EACF,OAA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ACA,MACA,SACF;CACA,IAAI,CAAC,UAAU,IACb,OAAO,mBAAmB;EACxB,aAAa;GAAE,WAAW,CAAC;GAAG,aAAa,CAAC;EAAE;EAC9C;EACA,gBAAgB,CAAC,UAAU,OAAO;CACpC,CAAC;CAEH,MAAM,cAAc,wBAAwB,UAAU,WAAW,EAC/D,WAAW,gBACb,CAAC;CACD,MAAM,gBAAgB,MAAM,oBAC1B,aACA,QAAQ,SACV;CACA,IAAI,CAAC,mBAAmB,WAAW,GACjC,OAAO,mBAAmB;EAAE;EAAa;EAAa;CAAc,CAAC;CAEvE,IACE,EACE,SAAS,KAAK,MAAM,aAAa,GAAG,EAClC,gBAAgB,MAClB,CAAC,CAAC,EAAE,OAAO,KAAK,QAGlB,OAAO,mBAAmB;EACxB;EACA;EACA;EACA,SAAS;CACX,CAAC;CAEH,MAAM,UAAU,MAAM,aAAa,SAAS,eAAe,MAAM,SAAS;CAC1E,OAAO,mBACL,QAAQ,KACJ;EAAE;EAAa;EAAa;EAAe,SAAS,QAAQ;CAAU,IACtE;EACE;EACA;EACA;EACA,gBAAgB,CAAC,QAAQ,OAAO;CAClC,CACN;AACF","debug_id":"3f8fce55-4f50-526a-9192-6274d6131949"}
|
|
@@ -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]="
|
|
3
|
-
import { t as getVersion } from "./get-version-
|
|
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]="b035721a-ca34-5898-abff-732183e61bc8")}catch(e){}}();
|
|
3
|
+
import { t as getVersion } from "./get-version-CIqOBtIW.mjs";
|
|
4
4
|
import { f as verifyReleaseApproval, i as revisionFiles, n as publishedFiles, o as packRelease, r as readReleaseApproval, s as packedDigests, u as decisionWithoutApproval } from "./files-D6_euBBn.mjs";
|
|
5
5
|
//#region src/services/release/verify.ts
|
|
6
6
|
/**
|
|
@@ -67,5 +67,5 @@ function checkApprovalBeforePublish(packageRoot, required) {
|
|
|
67
67
|
//#endregion
|
|
68
68
|
export { checkApprovalBeforePublish, renderReleaseDecision, verifyRelease };
|
|
69
69
|
|
|
70
|
-
//# sourceMappingURL=verify-
|
|
71
|
-
//# debugId=
|
|
70
|
+
//# sourceMappingURL=verify-CbhHneDD.mjs.map
|
|
71
|
+
//# debugId=b035721a-ca34-5898-abff-732183e61bc8
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verify-
|
|
1
|
+
{"version":3,"file":"verify-CbhHneDD.mjs","sources":["../src/services/release/verify.ts"],"sourcesContent":["import { getVersion } from \"../../get-version.js\";\nimport {\n type ApprovalRead,\n decisionWithoutApproval,\n type ReleaseDecision,\n verifyReleaseApproval,\n} from \"./approval.js\";\nimport { publishedFiles, readReleaseApproval, revisionFiles } from \"./files.js\";\nimport { packedDigests, packRelease, type PackedRelease } from \"./pack.js\";\nimport type { FileDigest } from \"./revision.js\";\n\n/**\n * Compares the package as it is now with its release approval: the files\n * the revision reads, with the output directory and exclusions the approval\n * records, and what `npm pack` publishes, or `published` when the caller\n * already packed it. Throws when either cannot be read.\n */\nexport function verifyRelease(\n packageRoot: string,\n read: ApprovalRead = readReleaseApproval(packageRoot),\n published?: readonly FileDigest[],\n): ReleaseDecision {\n if (read.kind !== \"found\") return decisionWithoutApproval(read);\n const { approval } = read;\n return verifyReleaseApproval(approval, {\n phCliVersion: getVersion(),\n files: revisionFiles(packageRoot, [\n approval.outDir,\n ...approval.packageRevision.excluded,\n ]),\n publishedFiles: published ?? publishedFiles(packageRoot),\n });\n}\n\nconst HEADLINES: Readonly<Record<ReleaseDecision[\"decision\"], string>> = {\n approved: \"the release approval matches this package\",\n missing: \"this package has no release approval\",\n unreadable: \"the release approval cannot be read\",\n stale: \"the release approval does not match this package\",\n refused: \"the release approval records a release check that did not pass\",\n};\n\n/** The decision and each reason on its own line. */\nexport function renderReleaseDecision(decision: ReleaseDecision): string {\n return [\n `${decision.decision}: ${HEADLINES[decision.decision]}`,\n ...decision.reasons.map((reason) => ` - ${reason}`),\n ].join(\"\\n\");\n}\n\n/**\n * Whether `ph publish` goes on. With `--require-approval`, `packed` is the\n * tarball the approval was checked against: publish that file, and call its\n * `dispose` once done.\n */\nexport type PublishCheck =\n | { readonly proceed: false }\n | { readonly proceed: true; readonly packed?: PackedRelease };\n\n/**\n * Checks the release approval before `ph publish` resolves a registry.\n * Without an approval file and without `required`, does nothing, as before\n * approvals existed. Otherwise a decision other than approved is a warning,\n * or with `required` a refusal.\n */\nexport function checkApprovalBeforePublish(\n packageRoot: string,\n required: boolean,\n): PublishCheck {\n const read = readReleaseApproval(packageRoot);\n if (read.kind === \"missing\" && !required) return { proceed: true };\n let text: string;\n let packed: PackedRelease | undefined;\n let approved = false;\n try {\n if (required && read.kind === \"found\") packed = packRelease(packageRoot);\n const decision = verifyRelease(\n packageRoot,\n read,\n packed && packedDigests(packed),\n );\n approved = decision.decision === \"approved\";\n text = renderReleaseDecision(decision);\n } catch (error) {\n text = `the release approval could not be checked: ${error instanceof Error ? error.message : String(error)}`;\n }\n if (approved) {\n console.log(`✔ ${text}`);\n return { proceed: true, packed };\n }\n packed?.dispose();\n if (required) {\n console.error(\n `✘ ${text}\\nph publish --require-approval publishes only an approved package. Run ph build --release, then publish again.`,\n );\n return { proceed: false };\n }\n console.warn(\n `⚠ ${text}\\nPublishing anyway. Run ph build --release to approve this package, or pass --require-approval to stop here instead.`,\n );\n return { proceed: true };\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAiBA,SAAgB,cACd,aACA,OAAqB,oBAAoB,WAAW,GACpD,WACiB;CACjB,IAAI,KAAK,SAAS,SAAS,OAA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
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]="
|
|
3
|
-
import { a as mergeDefaultDrives, c as rebaseDriveUrl, i as installStopChannel } from "./dist-
|
|
4
|
-
import { a as parseDefaultDrivesUrl, i as wasFlagExplicitlyPassed } from "./cli-connect-override-
|
|
5
|
-
import { t as runConnectStudio } from "./connect-studio-
|
|
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]="c85e2b19-c00d-5e83-b4a3-0b2948b091cb")}catch(e){}}();
|
|
3
|
+
import { a as mergeDefaultDrives, c as rebaseDriveUrl, i as installStopChannel } from "./dist-CuwtgEmh.mjs";
|
|
4
|
+
import { a as parseDefaultDrivesUrl, i as wasFlagExplicitlyPassed } from "./cli-connect-override-BRU7ykux.mjs";
|
|
5
|
+
import { t as runConnectStudio } from "./connect-studio-b53V1sw8.mjs";
|
|
6
|
+
import { a as syncMcpPortNotices, o as vetraRuntimeRecord, r as probeVetraRuntime, s as writeVetraRuntime, t as clearVetraRuntime } from "./vetra-runtime-kxkKcxOw.mjs";
|
|
6
7
|
import { a as generateProjectDriveId, s as getProjectInfo, t as POWERHOUSE_CONFIG_FILE } from "./utils-9KyRM0mf.mjs";
|
|
7
|
-
import {
|
|
8
|
-
import { i as stopVetra } from "./vetra-launch-
|
|
8
|
+
import { n as runVetraRefusal } from "./vetra-instance-B94ivpPZ.mjs";
|
|
9
|
+
import { i as stopVetra } from "./vetra-launch-sLUPOntK.mjs";
|
|
9
10
|
import { n as printVetraSwitchboardUrls, r as vetraProcessorConfigOf, t as configureVetraRemoteDrive } from "./vetra-switchboard-tzdc14KA.mjs";
|
|
10
11
|
import { join } from "node:path";
|
|
11
12
|
import { blue, green, red, yellow } from "colorette";
|
|
@@ -334,7 +335,13 @@ async function startVetra(args) {
|
|
|
334
335
|
printUrls,
|
|
335
336
|
bindCLIShortcuts,
|
|
336
337
|
watchTimeout
|
|
337
|
-
}, customViteLogger, vetraDrivesOverride, {
|
|
338
|
+
}, customViteLogger, vetraDrivesOverride, {
|
|
339
|
+
reloadOnConfigChange: true,
|
|
340
|
+
devPlugins: {
|
|
341
|
+
entries: [],
|
|
342
|
+
where: "ph vetra"
|
|
343
|
+
}
|
|
344
|
+
})).resolvedUrls?.local[0];
|
|
338
345
|
if (connectUrl && connectUrl !== runtimeRecord.connectUrl) writeVetraRuntime(projectDir, {
|
|
339
346
|
...runtimeRecord,
|
|
340
347
|
connectPort: Number(new URL(connectUrl).port) || connectPort,
|
|
@@ -348,5 +355,5 @@ async function startVetra(args) {
|
|
|
348
355
|
//#endregion
|
|
349
356
|
export { startVetra };
|
|
350
357
|
|
|
351
|
-
//# sourceMappingURL=vetra-
|
|
352
|
-
//# debugId=
|
|
358
|
+
//# sourceMappingURL=vetra-DR1C6-wd.mjs.map
|
|
359
|
+
//# debugId=c85e2b19-c00d-5e83-b4a3-0b2948b091cb
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vetra-CVNZ46pK.mjs","sources":["../src/utils/resolve-switchboard-port.ts","../src/services/vetra.ts"],"sourcesContent":["import { isPortAvailable } from \"@powerhousedao/switchboard/server\";\nimport { yellow } from \"colorette\";\n\nconst MAX_FALLBACK_ATTEMPTS = 20;\n\nfunction isInteractive(): boolean {\n return Boolean(process.stdin.isTTY) && !process.env.CI;\n}\n\nasync function findFreePort(start: number): Promise<number | null> {\n for (let i = 0; i < MAX_FALLBACK_ATTEMPTS; i++) {\n const candidate = start + i;\n if (await isPortAvailable(candidate)) return candidate;\n }\n return null;\n}\n\n/**\n * Resolve the port switchboard should bind to. If the requested port is free,\n * returns it unchanged. If it's in use, walks forward for the next free port\n * and — in an interactive terminal — asks the user to confirm the fallback.\n * In CI / piped contexts the fallback is applied automatically so scripts\n * don't hang on an unanswered prompt.\n *\n * Throws a process.exit(1) when the user declines the prompt or when no free\n * port is available in the search window.\n */\nexport async function resolveSwitchboardPort(\n requested: number,\n): Promise<number> {\n if (await isPortAvailable(requested)) return requested;\n\n const candidate = await findFreePort(requested + 1);\n if (candidate === null) {\n console.error(\n `Port ${requested} is in use and no free port was found in the range ${requested}-${requested + MAX_FALLBACK_ATTEMPTS - 1}.`,\n );\n process.exit(1);\n }\n\n if (!isInteractive()) {\n console.log(\n yellow(\n `Port ${requested} is in use. Falling back to port ${candidate} (non-interactive; skipping confirmation).`,\n ),\n );\n return candidate;\n }\n\n const enquirer = await import(\"enquirer\");\n\n let confirmed: boolean;\n try {\n const answer = await enquirer.default.prompt<{ confirmed: boolean }>({\n type: \"confirm\",\n name: \"confirmed\",\n message: `Port ${requested} is in use. Use port ${candidate} instead?`,\n initial: true,\n });\n confirmed = answer.confirmed;\n } catch {\n // user aborted the prompt (Ctrl-C); treat as decline\n confirmed = false;\n }\n\n if (!confirmed) {\n console.error(\n `Aborted. Free port ${requested} or pass --switchboard-port <port> to choose a different port.`,\n );\n process.exit(1);\n }\n\n return candidate;\n}\n","import { VETRA_PROCESSOR_CONFIG_KEY } from \"@powerhousedao/config\";\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport {\n getConfig,\n type PHConnectDefaultDrive,\n type PHConnectRuntimeConfig,\n} from \"@powerhousedao/shared/clis\";\nimport { addDefaultDrive } from \"@powerhousedao/switchboard/utils\";\nimport { join } from \"node:path\";\nimport { blue, green, red, yellow, type Color } from \"colorette\";\nimport type { ILogger } from \"document-model\";\nimport { childLogger, setLogLevel } from \"document-model\";\nimport { createLogger } from \"vite\";\nimport type { VetraArgs } from \"../types.js\";\nimport {\n generateProjectDriveId,\n getProjectInfo,\n POWERHOUSE_CONFIG_FILE,\n} from \"../utils.js\";\nimport { wasFlagExplicitlyPassed } from \"../utils/cli-connect-override.js\";\nimport {\n installStopChannel,\n mergeDefaultDrives,\n rebaseDriveUrl,\n} from \"@powerhousedao/host-core\";\nimport { parseDefaultDrivesUrl } from \"../utils/parse-default-drives.js\";\nimport { resolveSwitchboardPort } from \"../utils/resolve-switchboard-port.js\";\nimport {\n clearVetraRuntime,\n probeVetraRuntime,\n syncMcpPortNotices,\n vetraRuntimeRecord,\n writeVetraRuntime,\n} from \"../utils/vetra-runtime.js\";\nimport { stopVetra } from \"../utils/vetra-launch.js\";\nimport { runVetraRefusal } from \"../utils/vetra-instance.js\";\nimport { runConnectStudio } from \"./connect-studio.js\";\nimport {\n configureVetraRemoteDrive,\n printVetraSwitchboardUrls,\n vetraProcessorConfigOf,\n} from \"./vetra-switchboard.js\";\nimport {\n POWERHOUSE_DRIVE_ICON,\n seedWorkflowsDrive,\n startSwitchboard,\n} from \"@powerhousedao/ph-run/switchboard\";\n\nconst VETRA_DRIVE_NAME = \"vetra\";\n\nconst getDefaultVetraUrl = (port: number) =>\n `http://localhost:${port}/d/${generateProjectDriveId(VETRA_DRIVE_NAME)}`;\n\n// rebaseDriveUrl moved to @powerhousedao/host-core (uniform-runners P1.4) —\n// one implementation shared by this classic path and the generic compound.\n\nfunction createViteLogger(color: Color) {\n const customLogger = createLogger(\"info\");\n const loggerInfo = customLogger.info.bind(customLogger);\n customLogger.info = (msg, options) => {\n loggerInfo(color(msg), options);\n };\n const loggerWarn = customLogger.warn.bind(customLogger);\n customLogger.warn = (msg, options) => {\n loggerWarn(yellow(msg), options);\n };\n const loggerError = customLogger.error.bind(customLogger);\n customLogger.error = (msg, options) => {\n loggerError(red(msg), options);\n };\n\n const loggerWarnOnce = customLogger.warnOnce.bind(customLogger);\n customLogger.warnOnce = (msg, options) => {\n loggerWarnOnce(yellow(msg), options);\n };\n return customLogger;\n}\n\n/** Creates the Vetra Preview drive, or opens it, and opens it in `app` when given. */\nexport async function startVetraPreviewDrive(\n reactor: IReactorClient,\n port: number,\n verbose?: boolean,\n app?: string,\n): Promise<string | null> {\n const previewDriveId = generateProjectDriveId(\"preview\");\n\n const previewDrive = {\n id: previewDriveId,\n slug: previewDriveId,\n global: {\n name: \"Vetra Preview\",\n icon: POWERHOUSE_DRIVE_ICON,\n nodes: [],\n },\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\" as const,\n triggers: [],\n },\n };\n\n const driveUrl = await addDefaultDrive(\n reactor,\n { ...previewDrive, preferredEditor: app },\n port,\n );\n\n if (app && driveUrl) {\n await openDriveIn(reactor, previewDriveId, app);\n }\n\n if (verbose && driveUrl) {\n console.log(blue(`Vetra Switchboard: Preview drive: ${driveUrl}`));\n }\n return driveUrl ?? null;\n}\n\n/** Sets the drive's app unless it already has it; a drive from an earlier run keeps its old one otherwise. */\nasync function openDriveIn(\n reactor: IReactorClient,\n driveId: string,\n app: string,\n): Promise<void> {\n const drive = await reactor.read.get(driveId);\n if (drive.header.meta?.preferredEditor === app) {\n return;\n }\n const handle = await reactor.write.setPreferredEditor(driveId, app);\n await handle.readable;\n}\n\n// Studio's drives, read and written on the local Switchboard, so Studio and agents see one set\n// of drives (not with a remote Vetra drive, or a project that sets multiReactor or reactorClient), and no cookie banner.\nexport function buildVetraStudioOverride(\n defaultDrives: PHConnectDefaultDrive[],\n options: {\n remoteDrive?: string;\n projectConnect?: PHConnectRuntimeConfig;\n } = {},\n): PHConnectRuntimeConfig {\n const override: PHConnectRuntimeConfig = {\n drives: { defaultDrives, preserveStrategy: \"preserve-all\" },\n };\n // A first visit's cookie dialog covers the local Studio, agents' browsers included.\n if (options.projectConnect?.app?.cookieBanner === undefined) {\n override.app = { cookieBanner: false };\n }\n const instance = options.projectConnect?.instance;\n if (\n !options.remoteDrive &&\n instance?.multiReactor === undefined &&\n instance?.reactorClient === undefined\n ) {\n override.instance = {\n reactorClient: \"remote\",\n } as typeof override.instance;\n }\n return override;\n}\n\nasync function startLocalVetraSwitchboard(args: VetraArgs, logger?: ILogger) {\n const {\n connectPort,\n switchboardPort,\n dev,\n packages,\n disableLocalPackages,\n debug,\n httpsKeyFile,\n httpsCertFile,\n remoteDrive,\n interactive,\n watch,\n verbose,\n } = args;\n\n // Convert single remote drive to array if provided\n const remoteDrives = remoteDrive ? [remoteDrive] : [];\n\n const vetraDriveId = generateProjectDriveId(VETRA_DRIVE_NAME);\n\n const vetraProcessorConfig = vetraProcessorConfigOf({\n interactive,\n remoteDrive,\n localDriveUrl: getDefaultVetraUrl(connectPort),\n localDriveId: vetraDriveId,\n });\n\n const processorConfig = new Map<string, unknown>();\n processorConfig.set(VETRA_PROCESSOR_CONFIG_KEY, vetraProcessorConfig);\n\n // When the user didn't opt into strict-port semantics, check for a port\n // conflict up front and ask for confirmation before binding a fallback.\n // Doing this in the CLI layer keeps the interactive prompt out of the\n // switchboard server package and aligns with the existing prerelease-tag\n // confirmation flow in `ph publish`.\n const resolvedSwitchboardPort = args.strictPort\n ? switchboardPort\n : await resolveSwitchboardPort(switchboardPort);\n\n try {\n const switchboard = await startSwitchboard(\n {\n ...args,\n useVetraDrive: true, // Use Vetra drive instead of Powerhouse drive\n mcp: true,\n port: resolvedSwitchboardPort,\n // We've already probed and (when interactive) confirmed the port with\n // the user, so keep the server from running its own fallback on top.\n strictPort: true,\n dev,\n packages,\n remoteDrives,\n vetraDriveId,\n disableLocalPackages,\n debug,\n httpsKeyFile,\n httpsCertFile,\n processorConfig,\n basePath: undefined,\n keypairPath: undefined,\n dbPath: args.dbPath,\n useIdentity: undefined,\n migrate: undefined,\n migrateStatus: undefined,\n reset: undefined,\n yes: undefined,\n requireIdentity: undefined,\n },\n logger,\n );\n\n const actualSwitchboardPort = switchboard.port;\n\n // Add preview drive (only in watch mode)\n let previewDriveUrl: string | null = null;\n if (watch) {\n try {\n previewDriveUrl = await startVetraPreviewDrive(\n switchboard.reactor,\n actualSwitchboardPort,\n verbose,\n getConfig(join(process.cwd(), POWERHOUSE_CONFIG_FILE)).vetra\n ?.previewDrive?.app,\n );\n } catch (error) {\n console.error(error);\n }\n }\n\n let workflowsDriveUrl: string | null = null;\n if (switchboard.workflowsEnabled) {\n try {\n // Opens in Workflow Studio.\n workflowsDriveUrl = await seedWorkflowsDrive(\n switchboard.reactor,\n actualSwitchboardPort,\n getProjectInfo().path,\n );\n if (verbose && workflowsDriveUrl) {\n console.log(\n blue(`Vetra Switchboard: Workflows drive: ${workflowsDriveUrl}`),\n );\n }\n } catch (error) {\n console.error(error);\n }\n }\n\n printVetraSwitchboardUrls({\n verbose,\n remoteDrive,\n switchboardPort: actualSwitchboardPort,\n driveUrl: switchboard.defaultDriveUrl,\n previewDriveUrl,\n workflowsDriveUrl,\n });\n return {\n driveUrl: switchboard.defaultDriveUrl || \"\",\n previewDriveUrl: previewDriveUrl,\n workflowsDriveUrl,\n switchboardPort: actualSwitchboardPort,\n };\n } catch (error) {\n console.error(\n red(\n `Vetra Switchboard: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n throw error instanceof Error ? error : new Error(String(error));\n }\n}\n\nexport async function startVetra(args: VetraArgs) {\n const {\n connectPort,\n verbose,\n remoteDrive,\n disableConnect,\n debug,\n httpsCertFile,\n httpsKeyFile,\n disableLocalPackages,\n host,\n open,\n cors,\n strictPort,\n printUrls,\n bindCLIShortcuts,\n watchTimeout,\n } = args;\n\n const switchboardLogger = childLogger([\"vetra\", \"switchboard\"]);\n\n // One Vetra per project. Two instances over one working tree would contend\n // for the same `.ph/read-model.db` and `.ph/reactor-storage`, and leave the\n // project with two drives that diverge.\n const projectDir = process.cwd();\n const { readPackageSync } = await import(\"read-pkg\");\n const projectName = readPackageSync({ cwd: projectDir }).name;\n let probe = await probeVetraRuntime(projectDir, projectName);\n\n if (\n args.restart &&\n (probe.status === \"live\" || probe.status === \"starting\")\n ) {\n console.log(`Stopping this project's Vetra (pid ${probe.record.pid})...`);\n await stopVetra({ projectDir, projectName });\n probe = await probeVetraRuntime(projectDir, projectName);\n }\n\n if (probe.status === \"live\" || probe.status === \"starting\") {\n console.log();\n console.log(\n green(\n probe.status === \"live\"\n ? \"Vetra is already running for this project.\"\n : \"Vetra is already starting for this project.\",\n ),\n );\n const { record } = probe;\n console.log(\n green(\n ` ➜ Connect: ${record.connectUrl ?? `http://localhost:${record.connectPort}`}`,\n ),\n );\n console.log(\n green(\n ` ➜ Switchboard: ${record.switchboardUrl ?? `http://localhost:${record.switchboardPort}/graphql`}`,\n ),\n );\n console.log(\n `Run \\`ph vetra --restart\\` to restart it, or stop it (pid ${probe.record.pid}).`,\n );\n return;\n }\n\n if (probe.status === \"foreign\") {\n console.error(\n red(\n `.ph/vetra-runtime.json describes a live Vetra for \"${probe.record.projectName}\", ` +\n `but this project is \"${projectName}\". Refusing to start a second instance. ` +\n `Delete .ph/vetra-runtime.json if that record is wrong.`,\n ),\n );\n process.exit(1);\n }\n\n // The same project may be held by `ph run vetra` instead: its stack opens\n // the same stores, and publishes this record only once it is ready.\n const hostsRefusal = runVetraRefusal(projectDir, projectName);\n if (hostsRefusal) {\n console.error(red(hostsRefusal));\n process.exit(1);\n }\n\n try {\n // Set default log level to info if not already specified\n if (!process.env.LOG_LEVEL) {\n setLogLevel(\"info\");\n }\n\n if (verbose) {\n switchboardLogger.info(\"Starting Vetra Switchboard...\");\n if (remoteDrive) {\n const source = remoteDrive\n ? \"command line argument\"\n : \"powerhouse.config.json\";\n switchboardLogger.info(`Using vetraUrl from ${source}: ${remoteDrive}`);\n }\n }\n const switchboardResult = await startLocalVetraSwitchboard(\n {\n ...args,\n dev: true, // Vetra always runs in dev mode to load local packages\n httpsKeyFile,\n httpsCertFile,\n disableLocalPackages,\n debug,\n },\n switchboardLogger,\n );\n const driveUrl: string = switchboardResult.driveUrl || remoteDrive || \"\";\n const previewDriveUrl = switchboardResult.previewDriveUrl;\n const workflowsDriveUrl = switchboardResult.workflowsDriveUrl;\n const actualSwitchboardPort = switchboardResult.switchboardPort;\n\n // Record what we actually bound, so a second `ph vetra` can tell a live\n // instance from a stale file, and so an agent can see the real ports.\n const runtimeRecord = vetraRuntimeRecord({\n projectName,\n switchboardPort: actualSwitchboardPort,\n connectPort,\n ...(disableConnect\n ? {}\n : { connectUrl: `http://localhost:${connectPort}/` }),\n });\n writeVetraRuntime(projectDir, runtimeRecord);\n // A restarted Vetra may already have written its own.\n const releaseRuntimeRecord = () =>\n clearVetraRuntime(projectDir, process.pid);\n process.on(\"exit\", releaseRuntimeRecord);\n // `ph vetra --restart` stops this one through it on Windows.\n installStopChannel();\n process.on(\"SIGINT\", () => {\n releaseRuntimeRecord();\n process.exit(130);\n });\n process.on(\"SIGTERM\", () => {\n releaseRuntimeRecord();\n process.exit(143);\n });\n\n for (const notice of syncMcpPortNotices(\n projectDir,\n actualSwitchboardPort,\n )) {\n console.log(yellow(notice));\n }\n\n // Configure GitHub URL if remote drive is set\n if (remoteDrive) {\n await configureVetraRemoteDrive(\n actualSwitchboardPort,\n remoteDrive,\n verbose,\n );\n }\n\n if (verbose) {\n console.log(\"Starting Codegen Reactor...\");\n }\n\n // Start Connect pointing to the drive (unless disabled)\n if (!disableConnect) {\n // --drives-public-base: advertise proxy-reachable drive URLs to the\n // browser instead of the switchboard's localhost origin.\n const publicBase = args.drivesPublicBase;\n const browserDriveUrl = publicBase\n ? rebaseDriveUrl(driveUrl, publicBase)\n : driveUrl;\n const browserPreviewDriveUrl =\n previewDriveUrl && publicBase\n ? rebaseDriveUrl(previewDriveUrl, publicBase)\n : previewDriveUrl;\n const browserWorkflowsDriveUrl =\n workflowsDriveUrl && publicBase\n ? rebaseDriveUrl(workflowsDriveUrl, publicBase)\n : workflowsDriveUrl;\n\n // The resolved default-drive list: vetra's own drives first (the\n // Vetra drive, the preview drive in watch mode, and the Workflows\n // drive when workflows are on), then the\n // project's configured `connect.drives.defaultDrives` from\n // powerhouse.config.json (issue #3023). A drive vetra also starts is\n // listed only once. An explicit `--default-drives-url` is appended on\n // top of this list by buildStudioConnectOverride — it never replaces\n // the vetra drives.\n const vetraDriveEntries = [\n ...(browserDriveUrl\n ? [{ url: browserDriveUrl, name: null, icon: null }]\n : []),\n ...(browserPreviewDriveUrl\n ? [{ url: browserPreviewDriveUrl, name: null, icon: null }]\n : []),\n ...(browserWorkflowsDriveUrl\n ? [{ url: browserWorkflowsDriveUrl, name: null, icon: null }]\n : []),\n ];\n // Read again each time Studio restarts for a changed powerhouse.config.json.\n const studioDrives = () => {\n const projectConnect = getConfig(\n join(projectDir, POWERHOUSE_CONFIG_FILE),\n ).connect;\n const drives = mergeDefaultDrives(\n vetraDriveEntries,\n projectConnect?.drives?.defaultDrives ?? [],\n );\n return { projectConnect, drives };\n };\n const resolvedDefaultDrives = studioDrives().drives;\n\n if (verbose) {\n console.log(\"Starting Connect...\");\n // Mirror buildStudioConnectOverride: an explicit\n // --default-drives-url is appended to the resolved list.\n const flagDefaultDrives = wasFlagExplicitlyPassed(\"default-drives-url\")\n ? parseDefaultDrivesUrl(args.defaultDrivesUrl ?? \"\")\n : [];\n const printedDefaultDrives = mergeDefaultDrives(\n resolvedDefaultDrives,\n flagDefaultDrives,\n );\n console.log(\n ` ➜ Connect will use default drives: ${printedDefaultDrives\n .map((d) => (\"url\" in d ? d.url : `local:${d.id}`))\n .join(\", \")}`,\n );\n }\n console.log();\n console.log(green(`Vetra Connect: http://localhost:${connectPort}`));\n\n const customViteLogger = createViteLogger(green);\n\n // Programmatic override forwarded to the Connect runtime config —\n // vetra always sets these regardless of what the user typed on the\n // command line. We pass it as the explicit third arg to\n // runConnectStudio so it survives the `wasFlagExplicitlyPassed`\n // gating (the user didn't pass --default-drives-url; vetra is setting\n // it itself).\n const vetraDrivesOverride = () => {\n const { projectConnect, drives } = studioDrives();\n return buildVetraStudioOverride(drives, {\n remoteDrive,\n projectConnect,\n });\n };\n\n const studio = await runConnectStudio(\n {\n ...args,\n port: connectPort,\n disableLocalPackages,\n debug,\n host: host,\n open: open,\n cors: cors,\n strictPort: strictPort,\n printUrls: printUrls,\n bindCLIShortcuts: bindCLIShortcuts,\n watchTimeout: watchTimeout,\n },\n customViteLogger,\n vetraDrivesOverride,\n { reloadOnConfigChange: true },\n );\n // Vite may have taken another port, and the base path is Connect's.\n const connectUrl = studio.resolvedUrls?.local[0];\n if (connectUrl && connectUrl !== runtimeRecord.connectUrl) {\n writeVetraRuntime(projectDir, {\n ...runtimeRecord,\n connectPort: Number(new URL(connectUrl).port) || connectPort,\n connectUrl,\n });\n }\n }\n } catch (error) {\n console.error(error);\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAGA,MAAM,wBAAwB;AAE9B,SAAS,gBAAyB;CAChC,OAAO,QAAQ,QAAQ,MAAM,KAAK,KAAK,CAAC,QAAQ,IAAI;AACtD;AAEA,eAAe,aAAa,OAAuC;CACjE,KAAK,IAAI,IAAI,GAAG,IAAI,uBAAuB,KAAK;EAC9C,MAAM,YAAY,QAAQ;EAC1B,IAAI,MAAM,gBAAgB,SAAS,GAAG,OAAO;CAC/C;CACA,OAAO;AACT;;;;;;;;;;;AAYA,eAAsB,uBACpB,WACiB;CACjB,IAAI,MAAM,gBAAgB,SAAS,GAAG,OAAO;CAE7C,MAAM,YAAY,MAAM,aAAa,YAAY,CAAC;CAClD,IAAI,cAAc,MAAM;EACtB,QAAQ,MACN,QAAQ,UAAU,qDAAqD,UAAU,GAAG,YAAY,wBAAwB,EAAE,EAC5H;EACA,QAAQ,KAAK,CAAC;CAChB;CAEA,IAAI,CAAC,cAAc,GAAG;EACpB,QAAQ,IACN,OACE,QAAQ,UAAU,mCAAmC,UAAU,2CACjE,CACF;EACA,OAAO;CACT;CAEA,MAAM,WAAW,MAAM,OAAO;CAE9B,IAAI;CACJ,IAAI;EAOF,aAAY,MANS,SAAS,QAAQ,OAA+B;GACnE,MAAM;GACN,MAAM;GACN,SAAS,QAAQ,UAAU,uBAAuB,UAAU;GAC5D,SAAS;EACX,CAAC,EAAA,CACkB;CACrB,QAAQ;EAEN,YAAY;CACd;CAEA,IAAI,CAAC,WAAW;EACd,QAAQ,MACN,sBAAsB,UAAU,+DAClC;EACA,QA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B,IAClE,sBAAsB,KAAK,oBAAoB,EAAE,IACjD,CAAC;IACL,MAAM,uBAAuB,mBAC3B,uBACA,iBACF;IACA,QAAQ,IACN,yCAAyC,qBACtC,KAAK,MAAO,SAAS,IAAI,EAAE,MAAM,SAAS,EAAE,IAAK,CAAC,CAClD,KAAK,IAAI,GACd;GACF;GACA,QAAQ,IAAI;GACZ,QAAQ,IAAI,MAAM,mCAAmC,aAAa,CAAC;GAEnE,MAAM,mBAAmB,iBAAiB,KAAK;GAQ/C,MAAM,4BAA4B;IAChC,MAAM,EAAE,gBAAgB,WAAW,aAAa;IAChD,OAAO,yBAAyB,QAAQ;KACtC;KACA;IACF,CAAC;GACH;GAqBA,MAAM,cAAa,MAnBE,iBACnB;IACE,GAAG;IACH,MAAM;IACN;IACA;IACM;IACA;IACA;IACM;IACD;IACO;IACJ;GAChB,GACA,kBACA,qBACA,EAAE,sBAAsB,KAAK,CAC/B,EAAA,CAE0B,cAAc,MAAM;GAC9C,IAAI,cAAc,eAAe,cAAc,YAC7C,kBAAkB,YAAY;IAC5B,GAAG;IACH,aAAa,OAAO,IAAI,IAAI,UAAU,CAAC,CAAC,IAAI,KAAK;IACjD;GACF,CAAC;EAEL;CACF,SAAS,OAAO;EACd,QAAQ,MAAM,KAAK;CACrB;AACF","debug_id":"3ed4dd04-66f1-5195-a6c4-f37a92626c40"}
|
|
1
|
+
{"version":3,"file":"vetra-DR1C6-wd.mjs","sources":["../src/utils/resolve-switchboard-port.ts","../src/services/vetra.ts"],"sourcesContent":["import { isPortAvailable } from \"@powerhousedao/switchboard/server\";\nimport { yellow } from \"colorette\";\n\nconst MAX_FALLBACK_ATTEMPTS = 20;\n\nfunction isInteractive(): boolean {\n return Boolean(process.stdin.isTTY) && !process.env.CI;\n}\n\nasync function findFreePort(start: number): Promise<number | null> {\n for (let i = 0; i < MAX_FALLBACK_ATTEMPTS; i++) {\n const candidate = start + i;\n if (await isPortAvailable(candidate)) return candidate;\n }\n return null;\n}\n\n/**\n * Resolve the port switchboard should bind to. If the requested port is free,\n * returns it unchanged. If it's in use, walks forward for the next free port\n * and — in an interactive terminal — asks the user to confirm the fallback.\n * In CI / piped contexts the fallback is applied automatically so scripts\n * don't hang on an unanswered prompt.\n *\n * Throws a process.exit(1) when the user declines the prompt or when no free\n * port is available in the search window.\n */\nexport async function resolveSwitchboardPort(\n requested: number,\n): Promise<number> {\n if (await isPortAvailable(requested)) return requested;\n\n const candidate = await findFreePort(requested + 1);\n if (candidate === null) {\n console.error(\n `Port ${requested} is in use and no free port was found in the range ${requested}-${requested + MAX_FALLBACK_ATTEMPTS - 1}.`,\n );\n process.exit(1);\n }\n\n if (!isInteractive()) {\n console.log(\n yellow(\n `Port ${requested} is in use. Falling back to port ${candidate} (non-interactive; skipping confirmation).`,\n ),\n );\n return candidate;\n }\n\n const enquirer = await import(\"enquirer\");\n\n let confirmed: boolean;\n try {\n const answer = await enquirer.default.prompt<{ confirmed: boolean }>({\n type: \"confirm\",\n name: \"confirmed\",\n message: `Port ${requested} is in use. Use port ${candidate} instead?`,\n initial: true,\n });\n confirmed = answer.confirmed;\n } catch {\n // user aborted the prompt (Ctrl-C); treat as decline\n confirmed = false;\n }\n\n if (!confirmed) {\n console.error(\n `Aborted. Free port ${requested} or pass --switchboard-port <port> to choose a different port.`,\n );\n process.exit(1);\n }\n\n return candidate;\n}\n","import { VETRA_PROCESSOR_CONFIG_KEY } from \"@powerhousedao/config\";\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport {\n getConfig,\n type PHConnectDefaultDrive,\n type PHConnectRuntimeConfig,\n} from \"@powerhousedao/shared/clis\";\nimport { addDefaultDrive } from \"@powerhousedao/switchboard/utils\";\nimport { join } from \"node:path\";\nimport { blue, green, red, yellow, type Color } from \"colorette\";\nimport type { ILogger } from \"document-model\";\nimport { childLogger, setLogLevel } from \"document-model\";\nimport { createLogger } from \"vite\";\nimport type { VetraArgs } from \"../types.js\";\nimport {\n generateProjectDriveId,\n getProjectInfo,\n POWERHOUSE_CONFIG_FILE,\n} from \"../utils.js\";\nimport { wasFlagExplicitlyPassed } from \"../utils/cli-connect-override.js\";\nimport {\n installStopChannel,\n mergeDefaultDrives,\n rebaseDriveUrl,\n} from \"@powerhousedao/host-core\";\nimport { parseDefaultDrivesUrl } from \"../utils/parse-default-drives.js\";\nimport { resolveSwitchboardPort } from \"../utils/resolve-switchboard-port.js\";\nimport {\n clearVetraRuntime,\n probeVetraRuntime,\n syncMcpPortNotices,\n vetraRuntimeRecord,\n writeVetraRuntime,\n} from \"../utils/vetra-runtime.js\";\nimport { stopVetra } from \"../utils/vetra-launch.js\";\nimport { runVetraRefusal } from \"../utils/vetra-instance.js\";\nimport { runConnectStudio } from \"./connect-studio.js\";\nimport {\n configureVetraRemoteDrive,\n printVetraSwitchboardUrls,\n vetraProcessorConfigOf,\n} from \"./vetra-switchboard.js\";\nimport {\n POWERHOUSE_DRIVE_ICON,\n seedWorkflowsDrive,\n startSwitchboard,\n} from \"@powerhousedao/ph-run/switchboard\";\n\nconst VETRA_DRIVE_NAME = \"vetra\";\n\nconst getDefaultVetraUrl = (port: number) =>\n `http://localhost:${port}/d/${generateProjectDriveId(VETRA_DRIVE_NAME)}`;\n\n// rebaseDriveUrl moved to @powerhousedao/host-core (uniform-runners P1.4) —\n// one implementation shared by this classic path and the generic compound.\n\nfunction createViteLogger(color: Color) {\n const customLogger = createLogger(\"info\");\n const loggerInfo = customLogger.info.bind(customLogger);\n customLogger.info = (msg, options) => {\n loggerInfo(color(msg), options);\n };\n const loggerWarn = customLogger.warn.bind(customLogger);\n customLogger.warn = (msg, options) => {\n loggerWarn(yellow(msg), options);\n };\n const loggerError = customLogger.error.bind(customLogger);\n customLogger.error = (msg, options) => {\n loggerError(red(msg), options);\n };\n\n const loggerWarnOnce = customLogger.warnOnce.bind(customLogger);\n customLogger.warnOnce = (msg, options) => {\n loggerWarnOnce(yellow(msg), options);\n };\n return customLogger;\n}\n\n/** Creates the Vetra Preview drive, or opens it, and opens it in `app` when given. */\nexport async function startVetraPreviewDrive(\n reactor: IReactorClient,\n port: number,\n verbose?: boolean,\n app?: string,\n): Promise<string | null> {\n const previewDriveId = generateProjectDriveId(\"preview\");\n\n const previewDrive = {\n id: previewDriveId,\n slug: previewDriveId,\n global: {\n name: \"Vetra Preview\",\n icon: POWERHOUSE_DRIVE_ICON,\n nodes: [],\n },\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\" as const,\n triggers: [],\n },\n };\n\n const driveUrl = await addDefaultDrive(\n reactor,\n { ...previewDrive, preferredEditor: app },\n port,\n );\n\n if (app && driveUrl) {\n await openDriveIn(reactor, previewDriveId, app);\n }\n\n if (verbose && driveUrl) {\n console.log(blue(`Vetra Switchboard: Preview drive: ${driveUrl}`));\n }\n return driveUrl ?? null;\n}\n\n/** Sets the drive's app unless it already has it; a drive from an earlier run keeps its old one otherwise. */\nasync function openDriveIn(\n reactor: IReactorClient,\n driveId: string,\n app: string,\n): Promise<void> {\n const drive = await reactor.read.get(driveId);\n if (drive.header.meta?.preferredEditor === app) {\n return;\n }\n const handle = await reactor.write.setPreferredEditor(driveId, app);\n await handle.readable;\n}\n\n// Studio's drives, read and written on the local Switchboard, so Studio and agents see one set\n// of drives (not with a remote Vetra drive, or a project that sets multiReactor or reactorClient), and no cookie banner.\nexport function buildVetraStudioOverride(\n defaultDrives: PHConnectDefaultDrive[],\n options: {\n remoteDrive?: string;\n projectConnect?: PHConnectRuntimeConfig;\n } = {},\n): PHConnectRuntimeConfig {\n const override: PHConnectRuntimeConfig = {\n drives: { defaultDrives, preserveStrategy: \"preserve-all\" },\n };\n // A first visit's cookie dialog covers the local Studio, agents' browsers included.\n if (options.projectConnect?.app?.cookieBanner === undefined) {\n override.app = { cookieBanner: false };\n }\n const instance = options.projectConnect?.instance;\n if (\n !options.remoteDrive &&\n instance?.multiReactor === undefined &&\n instance?.reactorClient === undefined\n ) {\n override.instance = {\n reactorClient: \"remote\",\n } as typeof override.instance;\n }\n return override;\n}\n\nasync function startLocalVetraSwitchboard(args: VetraArgs, logger?: ILogger) {\n const {\n connectPort,\n switchboardPort,\n dev,\n packages,\n disableLocalPackages,\n debug,\n httpsKeyFile,\n httpsCertFile,\n remoteDrive,\n interactive,\n watch,\n verbose,\n } = args;\n\n // Convert single remote drive to array if provided\n const remoteDrives = remoteDrive ? [remoteDrive] : [];\n\n const vetraDriveId = generateProjectDriveId(VETRA_DRIVE_NAME);\n\n const vetraProcessorConfig = vetraProcessorConfigOf({\n interactive,\n remoteDrive,\n localDriveUrl: getDefaultVetraUrl(connectPort),\n localDriveId: vetraDriveId,\n });\n\n const processorConfig = new Map<string, unknown>();\n processorConfig.set(VETRA_PROCESSOR_CONFIG_KEY, vetraProcessorConfig);\n\n // When the user didn't opt into strict-port semantics, check for a port\n // conflict up front and ask for confirmation before binding a fallback.\n // Doing this in the CLI layer keeps the interactive prompt out of the\n // switchboard server package and aligns with the existing prerelease-tag\n // confirmation flow in `ph publish`.\n const resolvedSwitchboardPort = args.strictPort\n ? switchboardPort\n : await resolveSwitchboardPort(switchboardPort);\n\n try {\n const switchboard = await startSwitchboard(\n {\n ...args,\n useVetraDrive: true, // Use Vetra drive instead of Powerhouse drive\n mcp: true,\n port: resolvedSwitchboardPort,\n // We've already probed and (when interactive) confirmed the port with\n // the user, so keep the server from running its own fallback on top.\n strictPort: true,\n dev,\n packages,\n remoteDrives,\n vetraDriveId,\n disableLocalPackages,\n debug,\n httpsKeyFile,\n httpsCertFile,\n processorConfig,\n basePath: undefined,\n keypairPath: undefined,\n dbPath: args.dbPath,\n useIdentity: undefined,\n migrate: undefined,\n migrateStatus: undefined,\n reset: undefined,\n yes: undefined,\n requireIdentity: undefined,\n },\n logger,\n );\n\n const actualSwitchboardPort = switchboard.port;\n\n // Add preview drive (only in watch mode)\n let previewDriveUrl: string | null = null;\n if (watch) {\n try {\n previewDriveUrl = await startVetraPreviewDrive(\n switchboard.reactor,\n actualSwitchboardPort,\n verbose,\n getConfig(join(process.cwd(), POWERHOUSE_CONFIG_FILE)).vetra\n ?.previewDrive?.app,\n );\n } catch (error) {\n console.error(error);\n }\n }\n\n let workflowsDriveUrl: string | null = null;\n if (switchboard.workflowsEnabled) {\n try {\n // Opens in Workflow Studio.\n workflowsDriveUrl = await seedWorkflowsDrive(\n switchboard.reactor,\n actualSwitchboardPort,\n getProjectInfo().path,\n );\n if (verbose && workflowsDriveUrl) {\n console.log(\n blue(`Vetra Switchboard: Workflows drive: ${workflowsDriveUrl}`),\n );\n }\n } catch (error) {\n console.error(error);\n }\n }\n\n printVetraSwitchboardUrls({\n verbose,\n remoteDrive,\n switchboardPort: actualSwitchboardPort,\n driveUrl: switchboard.defaultDriveUrl,\n previewDriveUrl,\n workflowsDriveUrl,\n });\n return {\n driveUrl: switchboard.defaultDriveUrl || \"\",\n previewDriveUrl: previewDriveUrl,\n workflowsDriveUrl,\n switchboardPort: actualSwitchboardPort,\n };\n } catch (error) {\n console.error(\n red(\n `Vetra Switchboard: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n throw error instanceof Error ? error : new Error(String(error));\n }\n}\n\nexport async function startVetra(args: VetraArgs) {\n const {\n connectPort,\n verbose,\n remoteDrive,\n disableConnect,\n debug,\n httpsCertFile,\n httpsKeyFile,\n disableLocalPackages,\n host,\n open,\n cors,\n strictPort,\n printUrls,\n bindCLIShortcuts,\n watchTimeout,\n } = args;\n\n const switchboardLogger = childLogger([\"vetra\", \"switchboard\"]);\n\n // One Vetra per project. Two instances over one working tree would contend\n // for the same `.ph/read-model.db` and `.ph/reactor-storage`, and leave the\n // project with two drives that diverge.\n const projectDir = process.cwd();\n const { readPackageSync } = await import(\"read-pkg\");\n const projectName = readPackageSync({ cwd: projectDir }).name;\n let probe = await probeVetraRuntime(projectDir, projectName);\n\n if (\n args.restart &&\n (probe.status === \"live\" || probe.status === \"starting\")\n ) {\n console.log(`Stopping this project's Vetra (pid ${probe.record.pid})...`);\n await stopVetra({ projectDir, projectName });\n probe = await probeVetraRuntime(projectDir, projectName);\n }\n\n if (probe.status === \"live\" || probe.status === \"starting\") {\n console.log();\n console.log(\n green(\n probe.status === \"live\"\n ? \"Vetra is already running for this project.\"\n : \"Vetra is already starting for this project.\",\n ),\n );\n const { record } = probe;\n console.log(\n green(\n ` ➜ Connect: ${record.connectUrl ?? `http://localhost:${record.connectPort}`}`,\n ),\n );\n console.log(\n green(\n ` ➜ Switchboard: ${record.switchboardUrl ?? `http://localhost:${record.switchboardPort}/graphql`}`,\n ),\n );\n console.log(\n `Run \\`ph vetra --restart\\` to restart it, or stop it (pid ${probe.record.pid}).`,\n );\n return;\n }\n\n if (probe.status === \"foreign\") {\n console.error(\n red(\n `.ph/vetra-runtime.json describes a live Vetra for \"${probe.record.projectName}\", ` +\n `but this project is \"${projectName}\". Refusing to start a second instance. ` +\n `Delete .ph/vetra-runtime.json if that record is wrong.`,\n ),\n );\n process.exit(1);\n }\n\n // The same project may be held by `ph run vetra` instead: its stack opens\n // the same stores, and publishes this record only once it is ready.\n const hostsRefusal = runVetraRefusal(projectDir, projectName);\n if (hostsRefusal) {\n console.error(red(hostsRefusal));\n process.exit(1);\n }\n\n try {\n // Set default log level to info if not already specified\n if (!process.env.LOG_LEVEL) {\n setLogLevel(\"info\");\n }\n\n if (verbose) {\n switchboardLogger.info(\"Starting Vetra Switchboard...\");\n if (remoteDrive) {\n const source = remoteDrive\n ? \"command line argument\"\n : \"powerhouse.config.json\";\n switchboardLogger.info(`Using vetraUrl from ${source}: ${remoteDrive}`);\n }\n }\n const switchboardResult = await startLocalVetraSwitchboard(\n {\n ...args,\n dev: true, // Vetra always runs in dev mode to load local packages\n httpsKeyFile,\n httpsCertFile,\n disableLocalPackages,\n debug,\n },\n switchboardLogger,\n );\n const driveUrl: string = switchboardResult.driveUrl || remoteDrive || \"\";\n const previewDriveUrl = switchboardResult.previewDriveUrl;\n const workflowsDriveUrl = switchboardResult.workflowsDriveUrl;\n const actualSwitchboardPort = switchboardResult.switchboardPort;\n\n // Record what we actually bound, so a second `ph vetra` can tell a live\n // instance from a stale file, and so an agent can see the real ports.\n const runtimeRecord = vetraRuntimeRecord({\n projectName,\n switchboardPort: actualSwitchboardPort,\n connectPort,\n ...(disableConnect\n ? {}\n : { connectUrl: `http://localhost:${connectPort}/` }),\n });\n writeVetraRuntime(projectDir, runtimeRecord);\n // A restarted Vetra may already have written its own.\n const releaseRuntimeRecord = () =>\n clearVetraRuntime(projectDir, process.pid);\n process.on(\"exit\", releaseRuntimeRecord);\n // `ph vetra --restart` stops this one through it on Windows.\n installStopChannel();\n process.on(\"SIGINT\", () => {\n releaseRuntimeRecord();\n process.exit(130);\n });\n process.on(\"SIGTERM\", () => {\n releaseRuntimeRecord();\n process.exit(143);\n });\n\n for (const notice of syncMcpPortNotices(\n projectDir,\n actualSwitchboardPort,\n )) {\n console.log(yellow(notice));\n }\n\n // Configure GitHub URL if remote drive is set\n if (remoteDrive) {\n await configureVetraRemoteDrive(\n actualSwitchboardPort,\n remoteDrive,\n verbose,\n );\n }\n\n if (verbose) {\n console.log(\"Starting Codegen Reactor...\");\n }\n\n // Start Connect pointing to the drive (unless disabled)\n if (!disableConnect) {\n // --drives-public-base: advertise proxy-reachable drive URLs to the\n // browser instead of the switchboard's localhost origin.\n const publicBase = args.drivesPublicBase;\n const browserDriveUrl = publicBase\n ? rebaseDriveUrl(driveUrl, publicBase)\n : driveUrl;\n const browserPreviewDriveUrl =\n previewDriveUrl && publicBase\n ? rebaseDriveUrl(previewDriveUrl, publicBase)\n : previewDriveUrl;\n const browserWorkflowsDriveUrl =\n workflowsDriveUrl && publicBase\n ? rebaseDriveUrl(workflowsDriveUrl, publicBase)\n : workflowsDriveUrl;\n\n // The resolved default-drive list: vetra's own drives first (the\n // Vetra drive, the preview drive in watch mode, and the Workflows\n // drive when workflows are on), then the\n // project's configured `connect.drives.defaultDrives` from\n // powerhouse.config.json (issue #3023). A drive vetra also starts is\n // listed only once. An explicit `--default-drives-url` is appended on\n // top of this list by buildStudioConnectOverride — it never replaces\n // the vetra drives.\n const vetraDriveEntries = [\n ...(browserDriveUrl\n ? [{ url: browserDriveUrl, name: null, icon: null }]\n : []),\n ...(browserPreviewDriveUrl\n ? [{ url: browserPreviewDriveUrl, name: null, icon: null }]\n : []),\n ...(browserWorkflowsDriveUrl\n ? [{ url: browserWorkflowsDriveUrl, name: null, icon: null }]\n : []),\n ];\n // Read again each time Studio restarts for a changed powerhouse.config.json.\n const studioDrives = () => {\n const projectConnect = getConfig(\n join(projectDir, POWERHOUSE_CONFIG_FILE),\n ).connect;\n const drives = mergeDefaultDrives(\n vetraDriveEntries,\n projectConnect?.drives?.defaultDrives ?? [],\n );\n return { projectConnect, drives };\n };\n const resolvedDefaultDrives = studioDrives().drives;\n\n if (verbose) {\n console.log(\"Starting Connect...\");\n // Mirror buildStudioConnectOverride: an explicit\n // --default-drives-url is appended to the resolved list.\n const flagDefaultDrives = wasFlagExplicitlyPassed(\"default-drives-url\")\n ? parseDefaultDrivesUrl(args.defaultDrivesUrl ?? \"\")\n : [];\n const printedDefaultDrives = mergeDefaultDrives(\n resolvedDefaultDrives,\n flagDefaultDrives,\n );\n console.log(\n ` ➜ Connect will use default drives: ${printedDefaultDrives\n .map((d) => (\"url\" in d ? d.url : `local:${d.id}`))\n .join(\", \")}`,\n );\n }\n console.log();\n console.log(green(`Vetra Connect: http://localhost:${connectPort}`));\n\n const customViteLogger = createViteLogger(green);\n\n // Programmatic override forwarded to the Connect runtime config —\n // vetra always sets these regardless of what the user typed on the\n // command line. We pass it as the explicit third arg to\n // runConnectStudio so it survives the `wasFlagExplicitlyPassed`\n // gating (the user didn't pass --default-drives-url; vetra is setting\n // it itself).\n const vetraDrivesOverride = () => {\n const { projectConnect, drives } = studioDrives();\n return buildVetraStudioOverride(drives, {\n remoteDrive,\n projectConnect,\n });\n };\n\n const studio = await runConnectStudio(\n {\n ...args,\n port: connectPort,\n disableLocalPackages,\n debug,\n host: host,\n open: open,\n cors: cors,\n strictPort: strictPort,\n printUrls: printUrls,\n bindCLIShortcuts: bindCLIShortcuts,\n watchTimeout: watchTimeout,\n },\n customViteLogger,\n vetraDrivesOverride,\n {\n reloadOnConfigChange: true,\n devPlugins: { entries: [], where: \"ph vetra\" },\n },\n );\n // Vite may have taken another port, and the base path is Connect's.\n const connectUrl = studio.resolvedUrls?.local[0];\n if (connectUrl && connectUrl !== runtimeRecord.connectUrl) {\n writeVetraRuntime(projectDir, {\n ...runtimeRecord,\n connectPort: Number(new URL(connectUrl).port) || connectPort,\n connectUrl,\n });\n }\n }\n } catch (error) {\n console.error(error);\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAGA,MAAM,wBAAwB;AAE9B,SAAS,gBAAyB;CAChC,OAAO,QAAQ,QAAQ,MAAM,KAAK,KAAK,CAAC,QAAQ,IAAI;AACtD;AAEA,eAAe,aAAa,OAAuC;CACjE,KAAK,IAAI,IAAI,GAAG,IAAI,uBAAuB,KAAK;EAC9C,MAAM,YAAY,QAAQ;EAC1B,IAAI,MAAM,gBAAgB,SAAS,GAAG,OAAO;CAC/C;CACA,OAAO;AACT;;;;;;;;;;;AAYA,eAAsB,uBACpB,WACiB;CACjB,IAAI,MAAM,gBAAgB,SAAS,GAAG,OAAO;CAE7C,MAAM,YAAY,MAAM,aAAa,YAAY,CAAC;CAClD,IAAI,cAAc,MAAM;EACtB,QAAQ,MACN,QAAQ,UAAU,qDAAqD,UAAU,GAAG,YAAY,wBAAwB,EAAE,EAC5H;EACA,QAAQ,KAAK,CAAC;CAChB;CAEA,IAAI,CAAC,cAAc,GAAG;EACpB,QAAQ,IACN,OACE,QAAQ,UAAU,mCAAmC,UAAU,2CACjE,CACF;EACA,OAAO;CACT;CAEA,MAAM,WAAW,MAAM,OAAO;CAE9B,IAAI;CACJ,IAAI;EAOF,aAAY,MANS,SAAS,QAAQ,OAA+B;GACnE,MAAM;GACN,MAAM;GACN,SAAS,QAAQ,UAAU,uBAAuB,UAAU;GAC5D,SAAS;EACX,CAAC,EAAA,CACkB;CACrB,QAAQ;EAEN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GAE7C,IAAI,SAAS;IACX,QAAQ,IAAI,qBAAqB;IAGjC,MAAM,oBAAoB,wBAAwB,oBAAoB,IAClE,sBAAsB,KAAK,oBAAoB,EAAE,IACjD,CAAC;IACL,MAAM,uBAAuB,mBAC3B,uBACA,iBACF;IACA,QAAQ,IACN,yCAAyC,qBACtC,KAAK,MAAO,SAAS,IAAI,EAAE,MAAM,SAAS,EAAE,IAAK,CAAC,CAClD,KAAK,IAAI,GACd;GACF;GACA,QAAQ,IAAI;GACZ,QAAQ,IAAI,MAAM,mCAAmC,aAAa,CAAC;GAEnE,MAAM,mBAAmB,iBAAiB,KAAK;GAQ/C,MAAM,4BAA4B;IAChC,MAAM,EAAE,gBAAgB,WAAW,aAAa;IAChD,OAAO,yBAAyB,QAAQ;KACtC;KACA;IACF,CAAC;GACH;GAwBA,MAAM,cAAa,MAtBE,iBACnB;IACE,GAAG;IACH,MAAM;IACN;IACA;IACM;IACA;IACA;IACM;IACD;IACO;IACJ;GAChB,GACA,kBACA,qBACA;IACE,sBAAsB;IACtB,YAAY;KAAE,SAAS,CAAC;KAAG,OAAO;IAAW;GAC/C,CACF,EAAA,CAE0B,cAAc,MAAM;GAC9C,IAAI,cAAc,eAAe,cAAc,YAC7C,kBAAkB,YAAY;IAC5B,GAAG;IACH,aAAa,OAAO,IAAI,IAAI,UAAU,CAAC,CAAC,IAAI,KAAK;IACjD;GACF,CAAC;EAEL;CACF,SAAS,OAAO;EACd,QAAQ,MAAM,KAAK;CACrB;AACF","debug_id":"c85e2b19-c00d-5e83-b4a3-0b2948b091cb"}
|
|
@@ -1,8 +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]="
|
|
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]="8301cbd8-30d9-59f8-8210-026bb2cb3ead")}catch(e){}}();
|
|
3
3
|
import { _ as unknown, d as object, r as array } from "./schemas-DzgKfQIx.mjs";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { H as readProjectName, a as STORE_VERBS, r as ONE_SHOT_VERBS } from "./compound-DKi56SSx-DAr69gXP.mjs";
|
|
5
|
+
import { a as syncMcpPortNotices, o as vetraRuntimeRecord, s as writeVetraRuntime, t as clearVetraRuntime } from "./vetra-runtime-kxkKcxOw.mjs";
|
|
6
|
+
import { r as vetraRuntimeRefusal } from "./vetra-instance-B94ivpPZ.mjs";
|
|
6
7
|
import { yellow } from "colorette";
|
|
7
8
|
import { outputsSchema } from "@powerhousedao/ph-run/runners/connect";
|
|
8
9
|
import { outputsSchema as outputsSchema$1 } from "@powerhousedao/ph-run/runners/switchboard";
|
|
@@ -75,5 +76,5 @@ function publishVetraRuntime(projectDir, projectName, result) {
|
|
|
75
76
|
//#endregion
|
|
76
77
|
export { runVetraHost };
|
|
77
78
|
|
|
78
|
-
//# sourceMappingURL=vetra-host-
|
|
79
|
-
//# debugId=
|
|
79
|
+
//# sourceMappingURL=vetra-host-CHcHhb97.mjs.map
|
|
80
|
+
//# debugId=8301cbd8-30d9-59f8-8210-026bb2cb3ead
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vetra-host-
|
|
1
|
+
{"version":3,"file":"vetra-host-CHcHhb97.mjs","sources":["../src/services/run/vetra-host.ts"],"sourcesContent":["import {\n ONE_SHOT_VERBS,\n readProjectName,\n STORE_VERBS,\n} from \"@powerhousedao/host-core\";\nimport { outputsSchema as connectOutputsSchema } from \"@powerhousedao/ph-run/runners/connect\";\nimport { outputsSchema as switchboardOutputsSchema } from \"@powerhousedao/ph-run/runners/switchboard\";\nimport { startRun, type StartRunArgs } from \"@powerhousedao/ph-run/start-run\";\nimport { yellow } from \"colorette\";\nimport { z } from \"zod\";\nimport { vetraRuntimeRefusal } from \"../../utils/vetra-instance.js\";\nimport {\n clearVetraRuntime,\n syncMcpPortNotices,\n vetraRuntimeRecord,\n writeVetraRuntime,\n type VetraRuntimeRecord,\n} from \"../../utils/vetra-runtime.js\";\n\n/**\n * `ph run vetra`: the vetra host is the generic compound runner over a\n * switchboard and a connect member, so nothing below `ph run` knows it is\n * Vetra. What `ph vetra` does around its own start is done here around\n * startRun instead, with the same helpers: refuse while another Vetra holds\n * the project, publish `.ph/vetra-runtime.json` once the stack is ready,\n * clear it on exit, and correct a drifted `.mcp.json`.\n */\nexport async function runVetraHost(args: StartRunArgs): Promise<unknown> {\n const verb = args.verb ?? \"run\";\n // `build` starts nothing; a store verb is refused for a compound.\n if (ONE_SHOT_VERBS.has(verb) || STORE_VERBS.has(verb)) {\n return startRun(args);\n }\n const projectDir = args.projectRoot ?? process.cwd();\n const projectName = readProjectName(projectDir);\n const refusal = await vetraRuntimeRefusal(projectDir, projectName);\n if (refusal) throw new Error(refusal);\n\n const result = await startRun(args);\n publishVetraRuntime(projectDir, projectName, result);\n return result;\n}\n\nconst startedSchema = z.object({\n started: z.array(z.object({ outputs: z.unknown() })),\n});\n\nconst portOf = (url: string) => Number(new URL(url).port);\n\nfunction firstMatch<T>(\n schema: z.ZodType<T>,\n candidates: unknown[],\n): T | undefined {\n for (const candidate of candidates) {\n const match = schema.safeParse(candidate);\n if (match.success) return match.data;\n }\n return undefined;\n}\n\n/**\n * The record of a ready compound: its members are told apart by the outputs\n * their runners publish, since a host file is free to name them.\n */\nexport function vetraRecordOfRun(\n projectName: string,\n result: unknown,\n): VetraRuntimeRecord | undefined {\n const parsed = startedSchema.safeParse(result);\n const outputs = parsed.success\n ? parsed.data.started.map((member) => member.outputs)\n : [];\n const switchboard = firstMatch(switchboardOutputsSchema, outputs);\n if (!switchboard) return undefined;\n const connect = firstMatch(connectOutputsSchema, outputs);\n return vetraRuntimeRecord({\n projectName,\n switchboardPort: portOf(switchboard.origin),\n // Vite may have taken another port, and the base path is Connect's.\n connectPort: connect ? portOf(connect.origin) : 0,\n switchboardUrl: switchboard.endpoints.graphql,\n mcpUrl: switchboard.endpoints.mcp,\n connectUrl: connect?.endpoints.connect,\n });\n}\n\n/**\n * Publishes the record of the stack startRun returned and syncs the MCP\n * configs to its port. Returns what clears the record again; it also runs on\n * exit. No SIGINT/SIGTERM handler: the compound owns the exit, and its\n * process.exit reaches the exit event.\n */\nexport function publishVetraRuntime(\n projectDir: string,\n projectName: string,\n result: unknown,\n): () => void {\n const record = vetraRecordOfRun(projectName, result);\n if (!record) {\n console.warn(\n yellow(\n \"No switchboard member is running, so .ph/vetra-runtime.json is not written and `ph mcp` will not find this stack.\",\n ),\n );\n return () => {};\n }\n // Record what the stack actually bound, so a second Vetra can tell a live\n // instance from a stale file, and so an agent can see the real ports.\n writeVetraRuntime(projectDir, record);\n // A restarted Vetra may already have written its own.\n const release = () => clearVetraRuntime(projectDir, process.pid);\n process.on(\"exit\", release);\n\n for (const notice of syncMcpPortNotices(projectDir, record.switchboardPort)) {\n console.log(yellow(notice));\n }\n return release;\n}\n"],"names":["z.object","z.array","z.unknown","switchboardOutputsSchema","connectOutputsSchema"],"mappings":";;;;;;;;;;;;;;;;;;;AA2BA,eAAsB,aAAa,MAAsC;CACvE,MAAM,OAAO,KAAK,QAAQ;CAE1B,IAAI,eAAe,IAAI,IAAI,KAAK,YAAY,IAAI,IAAI,GAClD,OAAO,SAAS,IAAI;CAEtB,MAAM,aAAa,KAAK,eAAe,QAAQ,IAAI;CACnD,MAAM,cAAc,gBAAgB,UAAU;CAC9C,MAAM,UAAU,MAAM,oBAAoB,YAAY,WAAW;CACjE,IAAI,SAAS,MAAM,IAAI,MAAM,OAAO;CAEpC,MAAM,SAAS,MAAM,SAAS,IAAI;CAClC,oBAAoB,YAAY,aAAa,MAAM;CACnD,OAAO;AACT;AAEA,MA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
|
+
!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]="bd34fa7f-0303-54c5-96b3-c3b7f18e42b9")}catch(e){}}();
|
|
3
|
+
import { R as probeRun } from "./compound-DKi56SSx-DAr69gXP.mjs";
|
|
4
|
+
import { r as probeVetraRuntime } from "./vetra-runtime-kxkKcxOw.mjs";
|
|
5
|
+
//#region src/utils/vetra-instance.ts
|
|
6
|
+
/**
|
|
7
|
+
* One Vetra per project, whichever command started it. `ph vetra` records
|
|
8
|
+
* itself in `.ph/vetra-runtime.json`; `ph run vetra` records its stack in
|
|
9
|
+
* `.ph/run/vetra.json` and, once ready, in `.ph/vetra-runtime.json` too.
|
|
10
|
+
* Each start asks here whether the other kind holds the project.
|
|
11
|
+
*/
|
|
12
|
+
/** The host folder `ph vetra` routes to, and the name its host file carries. */
|
|
13
|
+
const VETRA_HOST = "vetra";
|
|
14
|
+
/** Why `ph vetra` must not start: a live `ph run vetra` holds the project. */
|
|
15
|
+
function runVetraRefusal(projectDir, projectName) {
|
|
16
|
+
const probe = probeRun(projectDir, VETRA_HOST, projectName);
|
|
17
|
+
if (probe.status === "live" && probe.record.pid !== process.pid) return `Vetra is already running for this project through \`ph run ${VETRA_HOST}\` (pid ${probe.record.pid}). Stop it before starting another.`;
|
|
18
|
+
if (probe.status === "foreign") return `.ph/run/${VETRA_HOST}.json describes a live "${probe.record.projectName}", but this project is "${projectName}". Refusing to start a second instance.`;
|
|
19
|
+
}
|
|
20
|
+
/** Why `ph run vetra` must not start: a live Vetra holds the project. */
|
|
21
|
+
async function vetraRuntimeRefusal(projectDir, projectName) {
|
|
22
|
+
const probe = await probeVetraRuntime(projectDir, projectName);
|
|
23
|
+
if (probe.status === "live" || probe.status === "starting") {
|
|
24
|
+
if (probe.record.pid === process.pid) return void 0;
|
|
25
|
+
return `Vetra is already running for this project (pid ${probe.record.pid}). Stop it before starting another.`;
|
|
26
|
+
}
|
|
27
|
+
if (probe.status === "foreign") return `.ph/vetra-runtime.json describes a live Vetra for "${probe.record.projectName}", but this project is "${projectName}". Refusing to start a second instance. Delete .ph/vetra-runtime.json if that record is wrong.`;
|
|
28
|
+
}
|
|
29
|
+
//#endregion
|
|
30
|
+
export { runVetraRefusal as n, vetraRuntimeRefusal as r, VETRA_HOST as t };
|
|
31
|
+
|
|
32
|
+
//# sourceMappingURL=vetra-instance-B94ivpPZ.mjs.map
|
|
33
|
+
//# debugId=bd34fa7f-0303-54c5-96b3-c3b7f18e42b9
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vetra-instance-B94ivpPZ.mjs","sources":["../src/utils/vetra-instance.ts"],"sourcesContent":["import { probeRun } from \"@powerhousedao/host-core\";\nimport { probeVetraRuntime } from \"./vetra-runtime.js\";\n\n/**\n * One Vetra per project, whichever command started it. `ph vetra` records\n * itself in `.ph/vetra-runtime.json`; `ph run vetra` records its stack in\n * `.ph/run/vetra.json` and, once ready, in `.ph/vetra-runtime.json` too.\n * Each start asks here whether the other kind holds the project.\n */\n\n/** The host folder `ph vetra` routes to, and the name its host file carries. */\nexport const VETRA_HOST = \"vetra\";\n\n/** Why `ph vetra` must not start: a live `ph run vetra` holds the project. */\nexport function runVetraRefusal(\n projectDir: string,\n projectName: string,\n): string | undefined {\n const probe = probeRun(projectDir, VETRA_HOST, projectName);\n if (probe.status === \"live\" && probe.record.pid !== process.pid) {\n return (\n `Vetra is already running for this project through \\`ph run ${VETRA_HOST}\\` ` +\n `(pid ${probe.record.pid}). Stop it before starting another.`\n );\n }\n if (probe.status === \"foreign\") {\n return (\n `.ph/run/${VETRA_HOST}.json describes a live \"${probe.record.projectName}\", ` +\n `but this project is \"${projectName}\". Refusing to start a second instance.`\n );\n }\n return undefined;\n}\n\n/** Why `ph run vetra` must not start: a live Vetra holds the project. */\nexport async function vetraRuntimeRefusal(\n projectDir: string,\n projectName: string,\n): Promise<string | undefined> {\n const probe = await probeVetraRuntime(projectDir, projectName);\n if (probe.status === \"live\" || probe.status === \"starting\") {\n if (probe.record.pid === process.pid) return undefined;\n return `Vetra is already running for this project (pid ${probe.record.pid}). Stop it before starting another.`;\n }\n if (probe.status === \"foreign\") {\n return (\n `.ph/vetra-runtime.json describes a live Vetra for \"${probe.record.projectName}\", ` +\n `but this project is \"${projectName}\". Refusing to start a second instance. ` +\n `Delete .ph/vetra-runtime.json if that record is wrong.`\n );\n }\n return undefined;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAWA,MAAa,aAAa;;AAG1B,SAAgB,gBACd,YACA,aACoB;CACpB,MAAM,QAAQ,SAAS,YAAY,YAAY,WAAW;CAC1D,IAAI,MAAM,WAAW,UAAU,MAAM,OAAO,QAAQ,QAAQ,KAC1D,OACE,8DAA8D,WAAW,UACjE,MAAM,OAAO,IAAI;CAG7B,IAAI,MAAM,WAAW,WACnB,OACE,WAAW,WAAW,0BAA0B,MAAM,OAAO,YAAY,0BACjD,YAAY;AAI1C;;AAGA,eAAsB,oBACpB,YACA,aAC6B;CAC7B,MAAM,QAAQ,MAAM,kBAAkB,YAAY,WAAW;CAC7D,IAAI,MAAM,WAAW,UAAU,MAAM,WAAW,YAAY;EAC1D,IAAI,MAAM,OAAO,QAAQ,QAAQ,KAAK,OAAO,KAAA;EAC7C,OAAO,kDAAkD,MAAM,OAAO,IAAI;CAC5E;CACA,IAAI,MAAM,WAAW,WACnB,OACE,sDAAsD,MAAM,OAAO,YAAY,0BACvD,YAAY;AAK1C","debug_id":"bd34fa7f-0303-54c5-96b3-c3b7f18e42b9"}
|
|
@@ -1,8 +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]="
|
|
3
|
-
import {
|
|
4
|
-
import { l as requestStop } from "./dist-
|
|
5
|
-
import {
|
|
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]="f80d6b98-6c42-551a-875d-78a73146dd9f")}catch(e){}}();
|
|
3
|
+
import { L as probeHostsFolder } from "./compound-DKi56SSx-DAr69gXP.mjs";
|
|
4
|
+
import { l as requestStop } from "./dist-CuwtgEmh.mjs";
|
|
5
|
+
import { n as isPortInUse, r as probeVetraRuntime, t as clearVetraRuntime } from "./vetra-runtime-kxkKcxOw.mjs";
|
|
6
|
+
import { t as VETRA_HOST } from "./vetra-instance-B94ivpPZ.mjs";
|
|
6
7
|
import fs from "node:fs";
|
|
7
8
|
import path from "node:path";
|
|
8
9
|
import { spawn } from "node:child_process";
|
|
@@ -233,5 +234,5 @@ async function restartVetra(options) {
|
|
|
233
234
|
//#endregion
|
|
234
235
|
export { vetraCommandFor as a, stopVetra as i, ensureVetra as n, restartVetra as r, VetraStartError as t };
|
|
235
236
|
|
|
236
|
-
//# sourceMappingURL=vetra-launch-
|
|
237
|
-
//# debugId=
|
|
237
|
+
//# sourceMappingURL=vetra-launch-sLUPOntK.mjs.map
|
|
238
|
+
//# debugId=f80d6b98-6c42-551a-875d-78a73146dd9f
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vetra-launch-qi10Unax.mjs","sources":["../src/utils/vetra-launch.ts"],"sourcesContent":["import { probeHostsFolder, requestStop } from \"@powerhousedao/host-core\";\nimport { resolvePhDir } from \"@powerhousedao/shared/clis/ph-dir\";\nimport { spawn } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { stripVTControlCharacters } from \"node:util\";\nimport { VETRA_HOST } from \"./vetra-instance.js\";\nimport {\n clearVetraRuntime,\n isPortInUse,\n probeVetraRuntime,\n type VetraRuntimeRecord,\n} from \"./vetra-runtime.js\";\n\nexport type VetraCommand = {\n command: string;\n args: string[];\n /** How messages name it; `ph vetra` when left out. */\n label?: string;\n};\n\nexport type EnsureVetraOptions = {\n projectDir: string;\n projectName: string;\n /** The port a strict-port Vetra will bind. */\n switchboardPort: number;\n command: VetraCommand;\n timeoutMs: number;\n pollMs?: number;\n /** Told what it waits on while Vetra is not ready yet, about once a second. */\n onProgress?: (message: string) => void;\n};\n\nexport class VetraStartError extends Error {}\n\nconst LOG_TAIL_LINES = 60;\nconst PORT_GRACE_MS = 10_000;\nconst STOP_TIMEOUT_MS = 15_000;\nconst PROGRESS_EVERY_MS = 1000;\n\nconst lockPath = (projectDir: string) =>\n path.join(resolvePhDir(projectDir), \"vetra-start.lock\");\n\nexport const vetraLogPath = (projectDir: string) =>\n path.join(resolvePhDir(projectDir), \"vetra.log\");\n\n// Forward slashes, so messages read the same on every platform.\nconst shownLogPath = (projectDir: string) =>\n path.relative(projectDir, vetraLogPath(projectDir)).split(path.sep).join(\"/\");\n\n/** `ph vetra --strictPort --watch` run by the ph-cli executing this code. */\nexport function currentPhCliVetraCommand(): VetraCommand {\n return {\n command: process.execPath,\n args: [process.argv[1], \"vetra\", \"--strictPort\", \"--watch\"],\n };\n}\n\n/** `ph run vetra --strictPort` run by the ph-cli executing this code. */\nexport function currentPhCliRunVetraCommand(): VetraCommand {\n return {\n command: process.execPath,\n args: [process.argv[1], \"run\", VETRA_HOST, \"--strictPort\"],\n label: `ph run ${VETRA_HOST}`,\n };\n}\n\n/**\n * What starts this project's Vetra: its `hosts/vetra` host when it has one,\n * as `ph vetra` itself routes there (run-sugar.ts), else classic `ph vetra`.\n * The host's own defaultVerb picks the verb; `--watch` is not a host argument.\n */\nexport function vetraCommandFor(projectDir: string): VetraCommand {\n const probe = probeHostsFolder(projectDir);\n return probe.kind === \"present\" && probe.hosts.includes(VETRA_HOST)\n ? currentPhCliRunVetraCommand()\n : currentPhCliVetraCommand();\n}\n\nfunction isPidAlive(pid: number | undefined): boolean {\n if (!pid) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\ntype LockRecord = { pid: number; vetraPid?: number };\n\nfunction readLock(projectDir: string): LockRecord | undefined {\n try {\n return JSON.parse(\n fs.readFileSync(lockPath(projectDir), \"utf8\"),\n ) as LockRecord;\n } catch {\n return undefined;\n }\n}\n\nfunction isLockHeld(lock: LockRecord | undefined): boolean {\n return !!lock && (isPidAlive(lock.pid) || isPidAlive(lock.vetraPid));\n}\n\n/** Held while the launcher or the Vetra it started is alive. */\nfunction tryAcquireLock(projectDir: string): boolean {\n const target = lockPath(projectDir);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n for (let attempt = 0; attempt < 2; attempt++) {\n try {\n fs.writeFileSync(target, JSON.stringify({ pid: process.pid }), {\n flag: \"wx\",\n });\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n if (isLockHeld(readLock(projectDir))) return false;\n fs.rmSync(target, { force: true });\n }\n }\n return false;\n}\n\nfunction releaseLock(projectDir: string): void {\n if (readLock(projectDir)?.pid === process.pid) {\n fs.rmSync(lockPath(projectDir), { force: true });\n }\n}\n\nexport function readLogTail(projectDir: string): string {\n try {\n const text = fs.readFileSync(vetraLogPath(projectDir), \"utf8\");\n const lines = stripVTControlCharacters(text).trimEnd().split(\"\\n\");\n return lines.slice(-LOG_TAIL_LINES).join(\"\\n\");\n } catch {\n return \"\";\n }\n}\n\nfunction withOutput(message: string, projectDir: string): VetraStartError {\n const tail = readLogTail(projectDir);\n const where = shownLogPath(projectDir);\n return new VetraStartError(\n tail\n ? `${message}\\n\\nVetra output (last lines of ${where}):\\n${tail}`\n : message,\n );\n}\n\nfunction foreignError(record: VetraRuntimeRecord): VetraStartError {\n return new VetraStartError(\n `.ph/vetra-runtime.json describes a live Vetra for \"${record.projectName}\" (pid ${record.pid}), not this project. ` +\n `Refusing to start a second reactor. Delete .ph/vetra-runtime.json if that record is wrong.`,\n );\n}\n\nasync function waitForLive(\n options: EnsureVetraOptions,\n deadline: number,\n stillStarting: () => boolean,\n): Promise<VetraRuntimeRecord | undefined> {\n const { projectDir, projectName, pollMs = 250, onProgress } = options;\n const startedAt = Date.now();\n let reportedAt = startedAt;\n while (Date.now() < deadline) {\n const probe = await probeVetraRuntime(projectDir, projectName);\n if (probe.status === \"live\") return probe.record;\n if (probe.status === \"foreign\") throw foreignError(probe.record);\n if (probe.status !== \"starting\" && !stillStarting()) return undefined;\n if (onProgress && Date.now() - reportedAt >= PROGRESS_EVERY_MS) {\n reportedAt = Date.now();\n const seconds = Math.round((reportedAt - startedAt) / 1000);\n onProgress(`Waiting for Vetra to be ready (${seconds}s)...`);\n }\n await sleep(pollMs);\n }\n return undefined;\n}\n\n/** This project's live Vetra, or a detached `ph vetra` started and awaited; never a second reactor. */\nexport async function ensureVetra(\n options: EnsureVetraOptions,\n): Promise<VetraRuntimeRecord> {\n const { projectDir, projectName, switchboardPort, timeoutMs } = options;\n const deadline = Date.now() + timeoutMs;\n const seconds = Math.round(timeoutMs / 1000);\n const report = options.onProgress ?? (() => {});\n\n const probe = await probeVetraRuntime(projectDir, projectName);\n if (probe.status === \"live\") return probe.record;\n if (probe.status === \"foreign\") throw foreignError(probe.record);\n if (probe.status === \"starting\") {\n report(`Vetra (pid ${probe.record.pid}) is starting; waiting for it...`);\n const record = await waitForLive(options, deadline, () => false);\n if (record) return record;\n throw withOutput(\n `Vetra (pid ${probe.record.pid}) is running but did not answer /ready within ${seconds}s.`,\n projectDir,\n );\n }\n\n while (!tryAcquireLock(projectDir)) {\n // Another launcher is starting Vetra for this project.\n report(\"Another process is starting Vetra for this project; waiting...\");\n const record = await waitForLive(options, deadline, () =>\n isLockHeld(readLock(projectDir)),\n );\n if (record) return record;\n if (Date.now() >= deadline) {\n throw withOutput(\n `Another process is starting Vetra for this project and it did not become ready within ${seconds}s.`,\n projectDir,\n );\n }\n }\n\n let keepLock = false;\n try {\n const again = await probeVetraRuntime(projectDir, projectName);\n if (again.status === \"live\") return again.record;\n if (again.status === \"foreign\") throw foreignError(again.record);\n\n if (again.status === \"starting\" || (await isPortInUse(switchboardPort))) {\n // Maybe a Vetra that bound the port but has not written its record yet.\n const grace = Date.now() + PORT_GRACE_MS;\n const record = await waitForLive(\n options,\n deadline,\n () => Date.now() < grace,\n );\n if (record) return record;\n throw new VetraStartError(\n `Port ${switchboardPort} is in use, but .ph/vetra-runtime.json names no live Vetra for this project. ` +\n `Stop whatever holds the port, or move this project's port (reactor.port in powerhouse.config.json).`,\n );\n }\n\n const logFile = vetraLogPath(projectDir);\n report(`Starting Vetra; its output goes to ${shownLogPath(projectDir)}...`);\n const logFd = fs.openSync(logFile, \"w\");\n let exit: { code: number | null; signal: string | null } | undefined;\n let spawnError: Error | undefined;\n const child = spawn(options.command.command, options.command.args, {\n cwd: projectDir,\n detached: true,\n stdio: [\"ignore\", logFd, logFd],\n windowsHide: true,\n });\n fs.closeSync(logFd);\n child.once(\"error\", (error) => (spawnError = error));\n child.once(\"exit\", (code, signal) => (exit = { code, signal }));\n child.unref();\n if (child.pid) {\n fs.writeFileSync(\n lockPath(projectDir),\n JSON.stringify({ pid: process.pid, vetraPid: child.pid }),\n );\n }\n\n const record = await waitForLive(\n options,\n deadline,\n () => !exit && !spawnError,\n );\n if (record) return record;\n\n if (spawnError) {\n throw new VetraStartError(\n `Could not run \\`${options.command.command}\\`: ${spawnError.message}`,\n );\n }\n if (exit) {\n const how =\n exit.signal !== null\n ? `was killed by ${exit.signal}`\n : `exited with code ${exit.code}`;\n throw withOutput(\n `\\`${options.command.label ?? \"ph vetra\"}\\` ${how} before it was ready.`,\n projectDir,\n );\n }\n // Still booting: keep the lock on its pid so the next call waits instead of spawning.\n keepLock = true;\n throw withOutput(\n `Vetra (pid ${child.pid}) did not answer /ready on port ${switchboardPort} within ${seconds}s. ` +\n `It is still running; the next tool call waits for it again.`,\n projectDir,\n );\n } finally {\n if (!keepLock) releaseLock(projectDir);\n }\n}\n\nasync function waitForExit(\n record: VetraRuntimeRecord,\n deadline: number,\n): Promise<boolean> {\n while (Date.now() < deadline) {\n const gone =\n !isPidAlive(record.pid) && !(await isPortInUse(record.switchboardPort));\n if (gone) return true;\n await sleep(100);\n }\n return false;\n}\n\n/** Stops this project's running Vetra, if any; resolves to the record it stopped. */\nexport async function stopVetra(options: {\n projectDir: string;\n projectName: string;\n timeoutMs?: number;\n onProgress?: (message: string) => void;\n}): Promise<VetraRuntimeRecord | undefined> {\n const { projectDir, projectName, timeoutMs = STOP_TIMEOUT_MS } = options;\n const probe = await probeVetraRuntime(projectDir, projectName);\n if (probe.status === \"foreign\") throw foreignError(probe.record);\n if (probe.status !== \"live\" && probe.status !== \"starting\") return undefined;\n const { record } = probe;\n const signal = (name: NodeJS.Signals) => {\n try {\n process.kill(record.pid, name);\n } catch {\n // Already gone.\n }\n };\n options.onProgress?.(`Stopping Vetra (pid ${record.pid})...`);\n // On Windows SIGTERM is a kill: ask through the stop channel, and signal\n // only a Vetra that has none.\n if (!(await requestStop(record.pid))) signal(\"SIGTERM\");\n if (!(await waitForExit(record, Date.now() + timeoutMs))) {\n signal(\"SIGKILL\");\n if (!(await waitForExit(record, Date.now() + timeoutMs))) {\n throw new VetraStartError(\n `Vetra (pid ${record.pid}) did not stop within ${Math.round((2 * timeoutMs) / 1000)}s.`,\n );\n }\n }\n clearVetraRuntime(projectDir, record.pid);\n if (readLock(projectDir)?.vetraPid === record.pid) {\n fs.rmSync(lockPath(projectDir), { force: true });\n }\n return record;\n}\n\n/** Stops this project's Vetra and starts it again, detached, as {@link ensureVetra} does. */\nexport async function restartVetra(\n options: EnsureVetraOptions,\n): Promise<VetraRuntimeRecord> {\n const { projectDir, projectName, onProgress } = options;\n const stopped = await stopVetra({ projectDir, projectName, onProgress });\n if (stopped) onProgress?.(`Stopped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kBAAkB,YAAY,OAAO,GAAG;CACxC,IAAI,SAAS,UAAU,CAAC,EAAE,aAAa,OAAO,KAC5C,GAAG,OAAO,SAAS,UAAU,GAAG,EAAE,OAAO,KAAK,CAAC;CAEjD,OAAO;AACT;;AAGA,eAAsB,aACpB,SAC6B;CAC7B,MAAM,EAAE,YAAY,aAAa,eAAe;CAChD,MAAM,UAAU,MAAM,UAAU;EAAE;EAAY;EAAa;CAAW,CAAC;CACvE,IAAI,SAAS,aAAa,sBAAsB,QAAQ,IAAI,GAAG;CAC/D,OAAO,YAAY,OAAO;AAC5B","debug_id":"827f4b69-ceb4-5e81-8ca7-b0a8261da2e0"}
|
|
1
|
+
{"version":3,"file":"vetra-launch-sLUPOntK.mjs","sources":["../src/utils/vetra-launch.ts"],"sourcesContent":["import { probeHostsFolder, requestStop } from \"@powerhousedao/host-core\";\nimport { resolvePhDir } from \"@powerhousedao/shared/clis/ph-dir\";\nimport { spawn } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { stripVTControlCharacters } from \"node:util\";\nimport { VETRA_HOST } from \"./vetra-instance.js\";\nimport {\n clearVetraRuntime,\n isPortInUse,\n probeVetraRuntime,\n type VetraRuntimeRecord,\n} from \"./vetra-runtime.js\";\n\nexport type VetraCommand = {\n command: string;\n args: string[];\n /** How messages name it; `ph vetra` when left out. */\n label?: string;\n};\n\nexport type EnsureVetraOptions = {\n projectDir: string;\n projectName: string;\n /** The port a strict-port Vetra will bind. */\n switchboardPort: number;\n command: VetraCommand;\n timeoutMs: number;\n pollMs?: number;\n /** Told what it waits on while Vetra is not ready yet, about once a second. */\n onProgress?: (message: string) => void;\n};\n\nexport class VetraStartError extends Error {}\n\nconst LOG_TAIL_LINES = 60;\nconst PORT_GRACE_MS = 10_000;\nconst STOP_TIMEOUT_MS = 15_000;\nconst PROGRESS_EVERY_MS = 1000;\n\nconst lockPath = (projectDir: string) =>\n path.join(resolvePhDir(projectDir), \"vetra-start.lock\");\n\nexport const vetraLogPath = (projectDir: string) =>\n path.join(resolvePhDir(projectDir), \"vetra.log\");\n\n// Forward slashes, so messages read the same on every platform.\nconst shownLogPath = (projectDir: string) =>\n path.relative(projectDir, vetraLogPath(projectDir)).split(path.sep).join(\"/\");\n\n/** `ph vetra --strictPort --watch` run by the ph-cli executing this code. */\nexport function currentPhCliVetraCommand(): VetraCommand {\n return {\n command: process.execPath,\n args: [process.argv[1], \"vetra\", \"--strictPort\", \"--watch\"],\n };\n}\n\n/** `ph run vetra --strictPort` run by the ph-cli executing this code. */\nexport function currentPhCliRunVetraCommand(): VetraCommand {\n return {\n command: process.execPath,\n args: [process.argv[1], \"run\", VETRA_HOST, \"--strictPort\"],\n label: `ph run ${VETRA_HOST}`,\n };\n}\n\n/**\n * What starts this project's Vetra: its `hosts/vetra` host when it has one,\n * as `ph vetra` itself routes there (run-sugar.ts), else classic `ph vetra`.\n * The host's own defaultVerb picks the verb; `--watch` is not a host argument.\n */\nexport function vetraCommandFor(projectDir: string): VetraCommand {\n const probe = probeHostsFolder(projectDir);\n return probe.kind === \"present\" && probe.hosts.includes(VETRA_HOST)\n ? currentPhCliRunVetraCommand()\n : currentPhCliVetraCommand();\n}\n\nfunction isPidAlive(pid: number | undefined): boolean {\n if (!pid) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\ntype LockRecord = { pid: number; vetraPid?: number };\n\nfunction readLock(projectDir: string): LockRecord | undefined {\n try {\n return JSON.parse(\n fs.readFileSync(lockPath(projectDir), \"utf8\"),\n ) as LockRecord;\n } catch {\n return undefined;\n }\n}\n\nfunction isLockHeld(lock: LockRecord | undefined): boolean {\n return !!lock && (isPidAlive(lock.pid) || isPidAlive(lock.vetraPid));\n}\n\n/** Held while the launcher or the Vetra it started is alive. */\nfunction tryAcquireLock(projectDir: string): boolean {\n const target = lockPath(projectDir);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n for (let attempt = 0; attempt < 2; attempt++) {\n try {\n fs.writeFileSync(target, JSON.stringify({ pid: process.pid }), {\n flag: \"wx\",\n });\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n if (isLockHeld(readLock(projectDir))) return false;\n fs.rmSync(target, { force: true });\n }\n }\n return false;\n}\n\nfunction releaseLock(projectDir: string): void {\n if (readLock(projectDir)?.pid === process.pid) {\n fs.rmSync(lockPath(projectDir), { force: true });\n }\n}\n\nexport function readLogTail(projectDir: string): string {\n try {\n const text = fs.readFileSync(vetraLogPath(projectDir), \"utf8\");\n const lines = stripVTControlCharacters(text).trimEnd().split(\"\\n\");\n return lines.slice(-LOG_TAIL_LINES).join(\"\\n\");\n } catch {\n return \"\";\n }\n}\n\nfunction withOutput(message: string, projectDir: string): VetraStartError {\n const tail = readLogTail(projectDir);\n const where = shownLogPath(projectDir);\n return new VetraStartError(\n tail\n ? `${message}\\n\\nVetra output (last lines of ${where}):\\n${tail}`\n : message,\n );\n}\n\nfunction foreignError(record: VetraRuntimeRecord): VetraStartError {\n return new VetraStartError(\n `.ph/vetra-runtime.json describes a live Vetra for \"${record.projectName}\" (pid ${record.pid}), not this project. ` +\n `Refusing to start a second reactor. Delete .ph/vetra-runtime.json if that record is wrong.`,\n );\n}\n\nasync function waitForLive(\n options: EnsureVetraOptions,\n deadline: number,\n stillStarting: () => boolean,\n): Promise<VetraRuntimeRecord | undefined> {\n const { projectDir, projectName, pollMs = 250, onProgress } = options;\n const startedAt = Date.now();\n let reportedAt = startedAt;\n while (Date.now() < deadline) {\n const probe = await probeVetraRuntime(projectDir, projectName);\n if (probe.status === \"live\") return probe.record;\n if (probe.status === \"foreign\") throw foreignError(probe.record);\n if (probe.status !== \"starting\" && !stillStarting()) return undefined;\n if (onProgress && Date.now() - reportedAt >= PROGRESS_EVERY_MS) {\n reportedAt = Date.now();\n const seconds = Math.round((reportedAt - startedAt) / 1000);\n onProgress(`Waiting for Vetra to be ready (${seconds}s)...`);\n }\n await sleep(pollMs);\n }\n return undefined;\n}\n\n/** This project's live Vetra, or a detached `ph vetra` started and awaited; never a second reactor. */\nexport async function ensureVetra(\n options: EnsureVetraOptions,\n): Promise<VetraRuntimeRecord> {\n const { projectDir, projectName, switchboardPort, timeoutMs } = options;\n const deadline = Date.now() + timeoutMs;\n const seconds = Math.round(timeoutMs / 1000);\n const report = options.onProgress ?? (() => {});\n\n const probe = await probeVetraRuntime(projectDir, projectName);\n if (probe.status === \"live\") return probe.record;\n if (probe.status === \"foreign\") throw foreignError(probe.record);\n if (probe.status === \"starting\") {\n report(`Vetra (pid ${probe.record.pid}) is starting; waiting for it...`);\n const record = await waitForLive(options, deadline, () => false);\n if (record) return record;\n throw withOutput(\n `Vetra (pid ${probe.record.pid}) is running but did not answer /ready within ${seconds}s.`,\n projectDir,\n );\n }\n\n while (!tryAcquireLock(projectDir)) {\n // Another launcher is starting Vetra for this project.\n report(\"Another process is starting Vetra for this project; waiting...\");\n const record = await waitForLive(options, deadline, () =>\n isLockHeld(readLock(projectDir)),\n );\n if (record) return record;\n if (Date.now() >= deadline) {\n throw withOutput(\n `Another process is starting Vetra for this project and it did not become ready within ${seconds}s.`,\n projectDir,\n );\n }\n }\n\n let keepLock = false;\n try {\n const again = await probeVetraRuntime(projectDir, projectName);\n if (again.status === \"live\") return again.record;\n if (again.status === \"foreign\") throw foreignError(again.record);\n\n if (again.status === \"starting\" || (await isPortInUse(switchboardPort))) {\n // Maybe a Vetra that bound the port but has not written its record yet.\n const grace = Date.now() + PORT_GRACE_MS;\n const record = await waitForLive(\n options,\n deadline,\n () => Date.now() < grace,\n );\n if (record) return record;\n throw new VetraStartError(\n `Port ${switchboardPort} is in use, but .ph/vetra-runtime.json names no live Vetra for this project. ` +\n `Stop whatever holds the port, or move this project's port (reactor.port in powerhouse.config.json).`,\n );\n }\n\n const logFile = vetraLogPath(projectDir);\n report(`Starting Vetra; its output goes to ${shownLogPath(projectDir)}...`);\n const logFd = fs.openSync(logFile, \"w\");\n let exit: { code: number | null; signal: string | null } | undefined;\n let spawnError: Error | undefined;\n const child = spawn(options.command.command, options.command.args, {\n cwd: projectDir,\n detached: true,\n stdio: [\"ignore\", logFd, logFd],\n windowsHide: true,\n });\n fs.closeSync(logFd);\n child.once(\"error\", (error) => (spawnError = error));\n child.once(\"exit\", (code, signal) => (exit = { code, signal }));\n child.unref();\n if (child.pid) {\n fs.writeFileSync(\n lockPath(projectDir),\n JSON.stringify({ pid: process.pid, vetraPid: child.pid }),\n );\n }\n\n const record = await waitForLive(\n options,\n deadline,\n () => !exit && !spawnError,\n );\n if (record) return record;\n\n if (spawnError) {\n throw new VetraStartError(\n `Could not run \\`${options.command.command}\\`: ${spawnError.message}`,\n );\n }\n if (exit) {\n const how =\n exit.signal !== null\n ? `was killed by ${exit.signal}`\n : `exited with code ${exit.code}`;\n throw withOutput(\n `\\`${options.command.label ?? \"ph vetra\"}\\` ${how} before it was ready.`,\n projectDir,\n );\n }\n // Still booting: keep the lock on its pid so the next call waits instead of spawning.\n keepLock = true;\n throw withOutput(\n `Vetra (pid ${child.pid}) did not answer /ready on port ${switchboardPort} within ${seconds}s. ` +\n `It is still running; the next tool call waits for it again.`,\n projectDir,\n );\n } finally {\n if (!keepLock) releaseLock(projectDir);\n }\n}\n\nasync function waitForExit(\n record: VetraRuntimeRecord,\n deadline: number,\n): Promise<boolean> {\n while (Date.now() < deadline) {\n const gone =\n !isPidAlive(record.pid) && !(await isPortInUse(record.switchboardPort));\n if (gone) return true;\n await sleep(100);\n }\n return false;\n}\n\n/** Stops this project's running Vetra, if any; resolves to the record it stopped. */\nexport async function stopVetra(options: {\n projectDir: string;\n projectName: string;\n timeoutMs?: number;\n onProgress?: (message: string) => void;\n}): Promise<VetraRuntimeRecord | undefined> {\n const { projectDir, projectName, timeoutMs = STOP_TIMEOUT_MS } = options;\n const probe = await probeVetraRuntime(projectDir, projectName);\n if (probe.status === \"foreign\") throw foreignError(probe.record);\n if (probe.status !== \"live\" && probe.status !== \"starting\") return undefined;\n const { record } = probe;\n const signal = (name: NodeJS.Signals) => {\n try {\n process.kill(record.pid, name);\n } catch {\n // Already gone.\n }\n };\n options.onProgress?.(`Stopping Vetra (pid ${record.pid})...`);\n // On Windows SIGTERM is a kill: ask through the stop channel, and signal\n // only a Vetra that has none.\n if (!(await requestStop(record.pid))) signal(\"SIGTERM\");\n if (!(await waitForExit(record, Date.now() + timeoutMs))) {\n signal(\"SIGKILL\");\n if (!(await waitForExit(record, Date.now() + timeoutMs))) {\n throw new VetraStartError(\n `Vetra (pid ${record.pid}) did not stop within ${Math.round((2 * timeoutMs) / 1000)}s.`,\n );\n }\n }\n clearVetraRuntime(projectDir, record.pid);\n if (readLock(projectDir)?.vetraPid === record.pid) {\n fs.rmSync(lockPath(projectDir), { force: true });\n }\n return record;\n}\n\n/** Stops this project's Vetra and starts it again, detached, as {@link ensureVetra} does. */\nexport async function restartVetra(\n options: EnsureVetraOptions,\n): Promise<VetraRuntimeRecord> {\n const { projectDir, projectName, onProgress } = options;\n const stopped = await stopVetra({ projectDir, projectName, onProgress });\n if (stopped) onProgress?.(`Stopped Vetra (pid ${stopped.pid}).`);\n return ensureVetra(options);\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAiCA,IAAa,kBAAb,cAAqC,MAAM,CAAC;AAG5C,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;AACxB,MAAM,oBAAoB;AAE1B,MAAM,YAAY,eAChB,KAAK,KAAK,aAAa,UAAU,GAAG,kBAAkB;AAExD,MAAa,gBAAgB,eAC3B,KAAK,KAAK,aAAa,UAAU,GAAG,WAAW;AAGjD,MAAM,gBAAgB,eACpB,KAAK,SAAS,YAAY,aAAa,UAAU,CAAC,CAAC,CAAC,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;;AAG9E,SAAgB,2BAAyC;CACvD,OAAO;EACL,SAAS,QAAQ;EACjB,MAAM;GAAC,QAAQ,KAAK;GA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typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
3
|
-
import { L as probeRun } from "./compound-DKi56SSx-CXQHhS6t.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]="3659f44e-51ed-51d5-bd30-cdb8c53ee9e3")}catch(e){}}();
|
|
4
3
|
import fs from "node:fs";
|
|
5
4
|
import path from "node:path";
|
|
6
5
|
import { resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
|
|
@@ -170,32 +169,7 @@ function syncMcpPortNotices(projectDir, port) {
|
|
|
170
169
|
return notices;
|
|
171
170
|
}
|
|
172
171
|
//#endregion
|
|
173
|
-
|
|
174
|
-
/**
|
|
175
|
-
* One Vetra per project, whichever command started it. `ph vetra` records
|
|
176
|
-
* itself in `.ph/vetra-runtime.json`; `ph run vetra` records its stack in
|
|
177
|
-
* `.ph/run/vetra.json` and, once ready, in `.ph/vetra-runtime.json` too.
|
|
178
|
-
* Each start asks here whether the other kind holds the project.
|
|
179
|
-
*/
|
|
180
|
-
/** The host folder `ph vetra` routes to, and the name its host file carries. */
|
|
181
|
-
const VETRA_HOST = "vetra";
|
|
182
|
-
/** Why `ph vetra` must not start: a live `ph run vetra` holds the project. */
|
|
183
|
-
function runVetraRefusal(projectDir, projectName) {
|
|
184
|
-
const probe = probeRun(projectDir, VETRA_HOST, projectName);
|
|
185
|
-
if (probe.status === "live" && probe.record.pid !== process.pid) return `Vetra is already running for this project through \`ph run ${VETRA_HOST}\` (pid ${probe.record.pid}). Stop it before starting another.`;
|
|
186
|
-
if (probe.status === "foreign") return `.ph/run/${VETRA_HOST}.json describes a live "${probe.record.projectName}", but this project is "${projectName}". Refusing to start a second instance.`;
|
|
187
|
-
}
|
|
188
|
-
/** Why `ph run vetra` must not start: a live Vetra holds the project. */
|
|
189
|
-
async function vetraRuntimeRefusal(projectDir, projectName) {
|
|
190
|
-
const probe = await probeVetraRuntime(projectDir, projectName);
|
|
191
|
-
if (probe.status === "live" || probe.status === "starting") {
|
|
192
|
-
if (probe.record.pid === process.pid) return void 0;
|
|
193
|
-
return `Vetra is already running for this project (pid ${probe.record.pid}). Stop it before starting another.`;
|
|
194
|
-
}
|
|
195
|
-
if (probe.status === "foreign") return `.ph/vetra-runtime.json describes a live Vetra for "${probe.record.projectName}", but this project is "${projectName}". Refusing to start a second instance. Delete .ph/vetra-runtime.json if that record is wrong.`;
|
|
196
|
-
}
|
|
197
|
-
//#endregion
|
|
198
|
-
export { isPortInUse as a, syncMcpPortNotices as c, clearVetraRuntime as i, vetraRuntimeRecord as l, runVetraRefusal as n, probeVetraRuntime as o, vetraRuntimeRefusal as r, readVetraRuntime as s, VETRA_HOST as t, writeVetraRuntime as u };
|
|
172
|
+
export { syncMcpPortNotices as a, readVetraRuntime as i, isPortInUse as n, vetraRuntimeRecord as o, probeVetraRuntime as r, writeVetraRuntime as s, clearVetraRuntime as t };
|
|
199
173
|
|
|
200
|
-
//# sourceMappingURL=vetra-
|
|
201
|
-
//# debugId=
|
|
174
|
+
//# sourceMappingURL=vetra-runtime-kxkKcxOw.mjs.map
|
|
175
|
+
//# debugId=3659f44e-51ed-51d5-bd30-cdb8c53ee9e3
|