Elffuss BraidHub

kikocis/continue public

main · 2.2 KiBRawPermalink
1import fs from "fs";
2
3import YAML from "yaml";
4
5import { logger } from "../util/logger.js";
6
7import {
8 PERMISSIONS_YAML_PATH,
9 PermissionsYamlConfig,
10 loadPermissionsYaml,
11} from "./permissionsYamlLoader.js";
12
13/**
14 * Generates a policy rule for a given tool call
15 * For most tools, returns the display name (e.g., "Read", "Write")
16 * For Bash tool, generates command-specific patterns like "Bash(ls*)"
17 */
18export function generatePolicyRule(toolName: string, toolArgs: any): string {
19 const normalizedName = toolName;
20
21 // For Bash tool, create command-specific policies
22 if (normalizedName === "Bash" && toolArgs?.command) {
23 const command = toolArgs.command.trim();
24 // Extract the first command (before pipes, &&, ||, etc.)
25 const firstCommand = command.split(/[;&|]|&&|\|\|/)[0]?.trim();
26 if (firstCommand) {
27 // Extract just the command name (before spaces or flags)
28 const commandName = firstCommand.split(/\s+/)[0];
29 return `Bash(${commandName}*)`;
30 }
31 }
32
33 // For all other tools, return the display name
34 return normalizedName;
35}
36
37/**
38 * Adds a policy rule to the permissions.yaml file
39 */
40export async function addPolicyToYaml(policyRule: string): Promise<void> {
41 try {
42 // Load existing config or create empty one
43 const config: PermissionsYamlConfig = loadPermissionsYaml() || {};
44
45 // Ensure allow array exists
46 if (!config.allow) {
47 config.allow = [];
48 }
49
50 // Add the policy if it doesn't already exist
51 if (config.allow.includes(policyRule)) {
52 logger.debug(`Policy rule already exists: ${policyRule}`);
53 } else {
54 config.allow.push(policyRule);
55
56 // Write the updated config back to the file
57 const yamlContent = YAML.stringify(config);
58
59 // Add header comment
60 const finalContent = `# Continue CLI Permissions Configuration
61# This file is managed by the Continue CLI and should not be edited manually.
62# Use the TUI to modify permissions interactively.
63
64${yamlContent}`;
65
66 await fs.promises.writeFile(PERMISSIONS_YAML_PATH, finalContent, "utf-8");
67 logger.info(`Added policy rule to permissions.yaml: ${policyRule}`);
68 }
69 } catch (error) {
70 logger.error("Failed to add policy to permissions.yaml", {
71 error,
72 policyRule,
73 });
74 throw error;
75 }
76}