Elffuss BraidHub

kikocis/continue public

fc89067dc2f1 · 7.4 KiBRawPermalink
1import JSZip from "jszip";
2
3import { env } from "./env.js";
4import { logger } from "./util/logger.js";
5
6/**
7 * Hub package type definitions
8 */
9export type HubPackageType = "rule" | "mcp" | "model" | "prompt";
10
11/**
12 * Hub package processor interface
13 */
14export interface HubPackageProcessor<T> {
15 type: HubPackageType;
16 expectedFileExtensions: string[];
17 parseContent(content: string, filename: string): Promise<T> | T;
18 validateContent?(content: T): boolean;
19}
20
21/**
22 * Rule processor - handles text content from .md files
23 */
24export const ruleProcessor: HubPackageProcessor<string> = {
25 type: "rule",
26 expectedFileExtensions: [".md"],
27 parseContent: (content: string) => content,
28};
29
30/**
31 * MCP processor - handles JSON/YAML configuration files
32 */
33export const mcpProcessor: HubPackageProcessor<any> = {
34 type: "mcp",
35 expectedFileExtensions: [".json", ".yaml", ".yml"],
36 parseContent: async (content: string, filename: string) => {
37 let parsed;
38 if (filename.endsWith(".json")) {
39 parsed = JSON.parse(content);
40 } else {
41 const yaml = await import("yaml");
42 parsed = yaml.parse(content);
43 }
44
45 // If the parsed content has an 'mcpServers' array, extract the first MCP server
46 // This handles hub packages that return a full config block
47 if (parsed.mcpServers && Array.isArray(parsed.mcpServers) && parsed.mcpServers.length > 0) {
48 return parsed.mcpServers[0];
49 }
50
51 return parsed;
52 },
53};
54
55/**
56 * Model processor - handles JSON/YAML configuration files
57 */
58export const modelProcessor: HubPackageProcessor<any> = {
59 type: "model",
60 expectedFileExtensions: [".json", ".yaml", ".yml"],
61 parseContent: async (content: string, filename: string) => {
62 let parsed;
63 if (filename.endsWith(".json")) {
64 parsed = JSON.parse(content);
65 } else {
66 const yaml = await import("yaml");
67 parsed = yaml.parse(content);
68 }
69
70 // If the parsed content has a 'models' array, extract the first model
71 // This handles hub packages that return a full config block
72 if (parsed.models && Array.isArray(parsed.models) && parsed.models.length > 0) {
73 return parsed.models[0];
74 }
75
76 return parsed;
77 },
78};
79
80/**
81 * Prompt processor - handles text content from .md files
82 */
83export const promptProcessor: HubPackageProcessor<string> = {
84 type: "prompt",
85 expectedFileExtensions: [".md", ".txt"],
86 parseContent: (content: string) => content,
87};
88
89/**
90 * Generic hub package loader
91 */
92export async function loadPackageFromHub<T>(
93 slug: string,
94 processor: HubPackageProcessor<T>,
95): Promise<T> {
96 const parts = slug.split("/");
97 if (parts.length !== 2) {
98 throw new Error(
99 `Invalid hub slug format. Expected "owner/package", got: ${slug}`,
100 );
101 }
102
103 const [ownerSlug, packageSlug] = parts;
104
105 // Use different endpoints based on package type
106 let downloadUrl: URL;
107 if (processor.type === "mcp" || processor.type === "model") {
108 // MCP and models use the registry endpoint
109 downloadUrl = new URL(
110 `registry/v1/${ownerSlug}/${packageSlug}/latest`,
111 env.apiBase,
112 );
113 } else {
114 // Rules and prompts use the v0 endpoint
115 downloadUrl = new URL(
116 `v0/${ownerSlug}/${packageSlug}/latest/download`,
117 env.apiBase,
118 );
119 }
120
121 try {
122 const response = await fetch(downloadUrl);
123
124 if (!response.ok) {
125 throw new Error(`HTTP ${response.status}: ${response.statusText}`);
126 }
127
128 // Check if this is a registry endpoint (returns JSON directly) or a zip file
129 if (processor.type === "mcp" || processor.type === "model") {
130 // Registry endpoints return JSON with a 'content' field containing YAML/JSON
131 const jsonResponse = await response.json();
132
133 // Extract and parse the content field
134 if (jsonResponse.content) {
135 // Parse the YAML/JSON content
136 const parsedContent = await processor.parseContent(
137 jsonResponse.content,
138 `${slug}.yaml`,
139 );
140 return parsedContent;
141 } else {
142 // If there's no content field, return the response as-is (backward compatibility)
143 return jsonResponse;
144 }
145 } else {
146 // v0 endpoints return zip files
147 const arrayBuffer = await response.arrayBuffer();
148 const zip = new JSZip();
149 const zipContents = await zip.loadAsync(arrayBuffer);
150
151 // Find files matching expected extensions
152 const matchingFiles = Object.keys(zipContents.files).filter((filename) => {
153 if (zipContents.files[filename].dir) return false;
154 return processor.expectedFileExtensions.some((ext) =>
155 filename.endsWith(ext),
156 );
157 });
158
159 if (matchingFiles.length === 0) {
160 throw new Error(
161 `No ${processor.type} content found in downloaded zip file. Expected files with extensions: ${processor.expectedFileExtensions.join(", ")}`,
162 );
163 }
164
165 // Use the first matching file
166 const contentFile = zipContents.files[matchingFiles[0]];
167 const rawContent = await contentFile.async("text");
168
169 // Parse content using the processor
170 const parsedContent = await processor.parseContent(
171 rawContent,
172 matchingFiles[0],
173 );
174
175 // Validate if processor has validation
176 if (processor.validateContent && !processor.validateContent(parsedContent)) {
177 throw new Error(`Invalid ${processor.type} content in ${matchingFiles[0]}`);
178 }
179
180 return parsedContent;
181 }
182 } catch (error: any) {
183 throw new Error(
184 `Failed to load ${processor.type} from hub "${slug}": ${error.message}`,
185 );
186 }
187}
188
189/**
190 * Convenience functions for specific package types
191 */
192export const loadRuleFromHub = (slug: string) =>
193 loadPackageFromHub(slug, ruleProcessor);
194
195export const loadMcpFromHub = (slug: string) =>
196 loadPackageFromHub(slug, mcpProcessor);
197
198export const loadModelFromHub = (slug: string) =>
199 loadPackageFromHub(slug, modelProcessor);
200
201export const loadPromptFromHub = (slug: string) =>
202 loadPackageFromHub(slug, promptProcessor);
203
204/**
205 * Process a rule specification - supports file paths, hub slugs, or direct content
206 */
207export async function processRule(ruleSpec: string): Promise<string> {
208 // If it looks like a hub slug (contains / but doesn't start with . or /)
209 if (
210 ruleSpec.includes("/") &&
211 !ruleSpec.startsWith(".") &&
212 !ruleSpec.startsWith("/")
213 ) {
214 return await loadRuleFromHub(ruleSpec);
215 }
216
217 // If it looks like a file path
218 if (
219 ruleSpec.includes(".") ||
220 ruleSpec.includes("/") ||
221 ruleSpec.includes("\\")
222 ) {
223 const fs = await import("fs");
224 const path = await import("path");
225
226 try {
227 const absolutePath = path.resolve(ruleSpec);
228 if (!fs.existsSync(absolutePath)) {
229 throw new Error(`Rule file not found: ${ruleSpec}`);
230 }
231 return fs.readFileSync(absolutePath, "utf-8");
232 } catch (error: any) {
233 throw new Error(`Failed to read rule file "${ruleSpec}": ${error.message}`);
234 }
235 }
236
237 // Otherwise, treat it as direct string content
238 return ruleSpec;
239}
240
241/**
242 * Batch load multiple packages with error handling
243 */
244export async function loadPackagesFromHub<T>(
245 slugs: string[],
246 processor: HubPackageProcessor<T>,
247): Promise<T[]> {
248 const results: T[] = [];
249
250 for (const slug of slugs) {
251 try {
252 const content = await loadPackageFromHub(slug, processor);
253 results.push(content);
254 } catch (error: any) {
255 logger.warn(`Failed to load ${processor.type} "${slug}": ${error.message}`);
256 }
257 }
258
259 return results;
260}