Elffuss BraidHub

kikocis/continue public

8eb3ae7b8d16 · 6.4 KiBRawPermalink
1import * as fs from "fs";
2import * as path from "path";
3
4import JSZip from "jszip";
5
6import { env } from "./env.js";
7
8export interface CommandLineArgs {
9 configPath?: string;
10 organizationSlug?: string; // Organization slug to use for this session
11 prompt?: string; // Optional prompt argument
12 resume?: boolean; // Resume from last session
13 readonly?: boolean; // Start in plan mode (backward compatibility)
14 rules?: string[]; // Array of rule specifications
15 prompts?: string[]; // Array of prompt specifications
16 format?: "json"; // Output format for headless mode
17}
18
19/**
20 * Load rule content from a file path
21 * @param filePath - Path to the rule file
22 * @returns The content of the rule file
23 */
24function loadRuleFromFile(filePath: string): string {
25 try {
26 const absolutePath = path.resolve(filePath);
27 if (!fs.existsSync(absolutePath)) {
28 throw new Error(`Rule file not found: ${filePath}`);
29 }
30 return fs.readFileSync(absolutePath, "utf-8");
31 } catch (error: any) {
32 throw new Error(`Failed to read rule file "${filePath}": ${error.message}`);
33 }
34}
35
36/**
37 * Load rule content from hub.continue.dev
38 * @param slug - The slug in format "owner/package"
39 * @returns The rule content from the hub
40 */
41async function loadRuleFromHub(slug: string): Promise<string> {
42 const parts = slug.split("/");
43 if (parts.length !== 2) {
44 throw new Error(
45 `Invalid hub slug format. Expected "owner/package", got: ${slug}`,
46 );
47 }
48
49 const [ownerSlug, ruleSlug] = parts;
50 const downloadUrl = new URL(
51 `v0/${ownerSlug}/${ruleSlug}/latest/download`,
52 env.apiBase,
53 );
54
55 try {
56 const response = await fetch(downloadUrl);
57
58 if (!response.ok) {
59 throw new Error(`HTTP ${response.status}: ${response.statusText}`);
60 }
61
62 // The API returns a zip file, so we need to extract the rule content
63 const arrayBuffer = await response.arrayBuffer();
64 const zip = new JSZip();
65 const zipContents = await zip.loadAsync(arrayBuffer);
66
67 // Find the first .md or .txt file (rule content)
68 const ruleFiles = Object.keys(zipContents.files).filter(
69 (filename) =>
70 filename.endsWith(".md") && !zipContents.files[filename].dir,
71 );
72
73 if (ruleFiles.length === 0) {
74 throw new Error("No rule content found in downloaded zip file");
75 }
76
77 // Use the first rule file found - TODO support multiple rules and parse frontmatter
78 const ruleFile = zipContents.files[ruleFiles[0]];
79 const content = await ruleFile.async("text");
80 return content;
81 } catch (error: any) {
82 throw new Error(`Failed to load rule from hub "${slug}": ${error.message}`);
83 }
84}
85
86/**
87 * Process a specification (rule or prompt) and return its content
88 * @param spec - Can be a file path, hub slug, or direct string content
89 * @returns The processed content
90 */
91export async function processPromptOrRule(spec: string): Promise<string> {
92 // If it looks like a hub slug (contains / but doesn't start with . or /)
93 if (spec.includes("/") && !spec.startsWith(".") && !spec.startsWith("/")) {
94 return await loadRuleFromHub(spec);
95 }
96
97 // If it looks like a file path (contains . or / or ends with common file extensions)
98 if (spec.includes(".") || spec.includes("/") || spec.includes("\\")) {
99 return loadRuleFromFile(spec);
100 }
101
102 // Otherwise, treat it as direct string content
103 return spec;
104}
105
106/**
107 * Parse command line arguments for non-permission related flags
108 * @deprecated Most functionality has been moved to services. This is only kept for backward compatibility.
109 * @returns Parsed command line arguments
110 */
111/* eslint-disable */
112export function parseArgs(): CommandLineArgs {
113 const args = process.argv.slice(2);
114
115 // Default values
116 const result: CommandLineArgs = {};
117
118 if (args.includes("--resume")) {
119 result.resume = true;
120 }
121
122 if (args.includes("--readonly")) {
123 result.readonly = true;
124 }
125
126 // Get format from --format flag
127 const formatIndex = args.indexOf("--format");
128 if (formatIndex !== -1 && formatIndex + 1 < args.length) {
129 const formatValue = args[formatIndex + 1];
130 if (formatValue === "json") {
131 result.format = "json";
132 }
133 }
134
135 // Get config path from --config flag
136 const configIndex = args.indexOf("--config");
137 if (configIndex !== -1 && configIndex + 1 < args.length) {
138 result.configPath = args[configIndex + 1];
139 }
140
141 // Get organization slug from --org flag
142 const orgIndex = args.indexOf("--org");
143 if (orgIndex !== -1 && orgIndex + 1 < args.length) {
144 const orgValue = args[orgIndex + 1];
145 // Convert "personal" to undefined right away to simplify downstream logic
146 result.organizationSlug =
147 orgValue.toLowerCase() === "personal" ? undefined : orgValue;
148 }
149
150 // Get rules from --rule flags (can be specified multiple times)
151 const ruleIndices: number[] = [];
152 for (let i = 0; i < args.length; i++) {
153 if (args[i] === "--rule") {
154 ruleIndices.push(i);
155 }
156 }
157
158 if (ruleIndices.length > 0) {
159 result.rules = [];
160 for (const ruleIndex of ruleIndices) {
161 if (ruleIndex + 1 < args.length) {
162 result.rules.push(args[ruleIndex + 1]);
163 }
164 }
165 }
166
167 // Get prompts from --prompt flags (can be specified multiple times)
168 const promptIndices: number[] = [];
169 for (let i = 0; i < args.length; i++) {
170 if (args[i] === "--prompt") {
171 promptIndices.push(i);
172 }
173 }
174
175 if (promptIndices.length > 0) {
176 result.prompts = [];
177 for (const promptIndex of promptIndices) {
178 if (promptIndex + 1 >= args.length) {
179 throw new Error("--prompt flag requires a value");
180 }
181
182 const promptValue = args[promptIndex + 1];
183
184 // Check if the next argument is actually another flag
185 if (promptValue.startsWith("--")) {
186 throw new Error("--prompt flag requires a value, found flag instead");
187 }
188
189 result.prompts.push(promptValue);
190 }
191 }
192
193 // Find the last argument that's not a flag or a flag value
194 const flagsWithValues = [
195 "--config",
196 "--org",
197 "--rule",
198 "--prompt",
199 "--format",
200 ];
201 const nonFlagArgs = args.filter((arg, index) => {
202 // Skip flags (starting with --)
203 if (arg.startsWith("--") || arg === "-p") return false;
204
205 // Skip flag values
206 const prevArg = index > 0 ? args[index - 1] : "";
207 if (flagsWithValues.includes(prevArg)) return false;
208
209 return true;
210 });
211
212 // If there are any non-flag arguments, use the last one as the prompt
213 if (nonFlagArgs.length > 0) {
214 result.prompt = nonFlagArgs[nonFlagArgs.length - 1];
215 }
216
217 return result;
218}