Elffuss BraidHub

kikocis/continue public

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