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