improved tool permissions UI
This commit is contained in:
parent
cf4f327c62
commit
248ff78216
16 changed files with 758 additions and 20 deletions
27
src/commands/BaseCommandOptions.ts
Normal file
27
src/commands/BaseCommandOptions.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
/**
|
||||
* Base interface for command options that are shared across multiple commands
|
||||
*/
|
||||
export interface BaseCommandOptions {
|
||||
/** Path to configuration file */
|
||||
config?: string;
|
||||
/** Array of rule specifications (can be file paths, hub slugs, or string content) */
|
||||
rule?: string[];
|
||||
/** Array of tools to allow (overrides default policies) */
|
||||
allow?: string[];
|
||||
/** Array of tools to ask permission for (overrides default policies) */
|
||||
ask?: string[];
|
||||
/** Array of tools to exclude from use (overrides default policies) */
|
||||
exclude?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Extended base options that include verbose and tool control flags
|
||||
*/
|
||||
export interface ExtendedCommandOptions extends BaseCommandOptions {
|
||||
/** Enable verbose logging */
|
||||
verbose?: boolean;
|
||||
/** Only allow readonly tools */
|
||||
readonly?: boolean;
|
||||
/** Disable all tools */
|
||||
noTools?: boolean;
|
||||
}
|
||||
|
|
@ -17,12 +17,11 @@ import { startTUIChat } from "../ui/index.js";
|
|||
import { safeStdout } from "../util/consoleOverride.js";
|
||||
import { formatError } from "../util/formatError.js";
|
||||
import logger from "../util/logger.js";
|
||||
import { BaseCommandOptions } from "./BaseCommandOptions.js";
|
||||
|
||||
export interface ChatOptions {
|
||||
export interface ChatOptions extends BaseCommandOptions {
|
||||
headless?: boolean;
|
||||
config?: string;
|
||||
resume?: boolean;
|
||||
rule?: string[]; // Array of rule specifications
|
||||
}
|
||||
|
||||
async function initializeChatHistory(
|
||||
|
|
@ -109,6 +108,11 @@ async function runHeadlessMode(
|
|||
configPath: options.config,
|
||||
rules: options.rule,
|
||||
headless: true,
|
||||
toolPermissionOverrides: {
|
||||
allow: options.allow,
|
||||
ask: options.ask,
|
||||
exclude: options.exclude,
|
||||
},
|
||||
});
|
||||
|
||||
// Get required services from the service container
|
||||
|
|
@ -174,7 +178,11 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
|
|||
console.log(CONTINUE_ASCII_ART);
|
||||
|
||||
// Start TUI immediately - it will handle service loading
|
||||
await startTUIChat(prompt, options.resume, options.config, options.rule);
|
||||
await startTUIChat(prompt, options.resume, options.config, options.rule, {
|
||||
allow: options.allow,
|
||||
ask: options.ask,
|
||||
exclude: options.exclude,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import {
|
|||
} from "../auth/workos.js";
|
||||
import { runNormalFlow } from "../onboarding.js";
|
||||
import { saveSession } from "../session.js";
|
||||
import { initializeServices } from "../services/index.js";
|
||||
import { streamChatResponse, type StreamCallbacks } from "../streamChatResponse.js";
|
||||
import { constructSystemMessage } from "../systemMessage.js";
|
||||
import telemetryService from "../telemetry/telemetryService.js";
|
||||
|
|
@ -19,15 +20,11 @@ import { getToolDisplayName } from "../tools.js";
|
|||
import { DisplayMessage } from "../ui/types.js";
|
||||
import { formatError } from "../util/formatError.js";
|
||||
import logger from "../util/logger.js";
|
||||
import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
interface ServeOptions {
|
||||
config?: string;
|
||||
readonly?: boolean;
|
||||
noTools?: boolean;
|
||||
verbose?: boolean;
|
||||
rule?: string[];
|
||||
interface ServeOptions extends ExtendedCommandOptions {
|
||||
timeout?: string;
|
||||
port?: string;
|
||||
}
|
||||
|
|
@ -50,6 +47,15 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
|
|||
const timeoutMs = timeoutSeconds * 1000;
|
||||
const port = parseInt(options.port || "8000", 10);
|
||||
|
||||
// Initialize services with tool permission overrides
|
||||
await initializeServices({
|
||||
toolPermissionOverrides: {
|
||||
allow: options.allow,
|
||||
ask: options.ask,
|
||||
exclude: options.exclude,
|
||||
},
|
||||
});
|
||||
|
||||
// Initialize authentication
|
||||
const authConfig = loadAuthConfig();
|
||||
|
||||
|
|
|
|||
60
src/index.ts
60
src/index.ts
|
|
@ -51,6 +51,36 @@ program
|
|||
},
|
||||
[] as string[]
|
||||
)
|
||||
.option(
|
||||
"--allow <tool>",
|
||||
"Allow specified tool (overrides default policies). Can be specified multiple times.",
|
||||
(value: string, previous: string[] | undefined) => {
|
||||
const array = Array.isArray(previous) ? previous : [];
|
||||
array.push(value);
|
||||
return array;
|
||||
},
|
||||
[] as string[]
|
||||
)
|
||||
.option(
|
||||
"--ask <tool>",
|
||||
"Ask for permission before using specified tool (overrides default policies). Can be specified multiple times.",
|
||||
(value: string, previous: string[] | undefined) => {
|
||||
const array = Array.isArray(previous) ? previous : [];
|
||||
array.push(value);
|
||||
return array;
|
||||
},
|
||||
[] as string[]
|
||||
)
|
||||
.option(
|
||||
"--exclude <tool>",
|
||||
"Exclude specified tool from use (overrides default policies). Can be specified multiple times.",
|
||||
(value: string, previous: string[] | undefined) => {
|
||||
const array = Array.isArray(previous) ? previous : [];
|
||||
array.push(value);
|
||||
return array;
|
||||
},
|
||||
[] as string[]
|
||||
)
|
||||
.action(async (prompt, options) => {
|
||||
// Configure console overrides FIRST, before any other logging
|
||||
const isHeadless = options.print;
|
||||
|
|
@ -131,6 +161,36 @@ program
|
|||
},
|
||||
[] as string[]
|
||||
)
|
||||
.option(
|
||||
"--allow <tool>",
|
||||
"Allow specified tool (overrides default policies). Can be specified multiple times.",
|
||||
(value: string, previous: string[] | undefined) => {
|
||||
const array = Array.isArray(previous) ? previous : [];
|
||||
array.push(value);
|
||||
return array;
|
||||
},
|
||||
[] as string[]
|
||||
)
|
||||
.option(
|
||||
"--ask <tool>",
|
||||
"Ask for permission before using specified tool (overrides default policies). Can be specified multiple times.",
|
||||
(value: string, previous: string[] | undefined) => {
|
||||
const array = Array.isArray(previous) ? previous : [];
|
||||
array.push(value);
|
||||
return array;
|
||||
},
|
||||
[] as string[]
|
||||
)
|
||||
.option(
|
||||
"--exclude <tool>",
|
||||
"Exclude specified tool from use (overrides default policies). Can be specified multiple times.",
|
||||
(value: string, previous: string[] | undefined) => {
|
||||
const array = Array.isArray(previous) ? previous : [];
|
||||
array.push(value);
|
||||
return array;
|
||||
},
|
||||
[] as string[]
|
||||
)
|
||||
.option(
|
||||
"--timeout <seconds>",
|
||||
"Inactivity timeout in seconds (default: 300)",
|
||||
|
|
|
|||
|
|
@ -6,20 +6,23 @@ import { ToolPermissionPolicy } from "./types.js";
|
|||
*/
|
||||
export const DEFAULT_TOOL_POLICIES: ToolPermissionPolicy[] = [
|
||||
// Read-only tools are generally safe to allow
|
||||
{ tool: "readFile", permission: "allow" },
|
||||
{ tool: "listFiles", permission: "allow" },
|
||||
{ tool: "searchCode", permission: "allow" },
|
||||
{ tool: "read_file", permission: "allow" },
|
||||
{ tool: "list_files", permission: "allow" },
|
||||
{ tool: "search_code", permission: "allow" },
|
||||
{ tool: "fetch", permission: "allow" },
|
||||
|
||||
// Write operations should require confirmation
|
||||
{ tool: "writeFile", permission: "ask" },
|
||||
{ tool: "write_file", permission: "ask" },
|
||||
|
||||
// Terminal commands should require confirmation by default
|
||||
{ tool: "runTerminalCommand", permission: "ask" },
|
||||
{ tool: "run_terminal_command", permission: "ask" },
|
||||
|
||||
// Exit tool is generally safe (headless mode only)
|
||||
{ tool: "exit", permission: "allow" },
|
||||
|
||||
// View diff is read-only
|
||||
{ tool: "view_diff", permission: "allow" },
|
||||
|
||||
// Default fallback - ask for any unmatched tools
|
||||
{ tool: "*", permission: "ask" },
|
||||
];
|
||||
|
|
|
|||
|
|
@ -227,11 +227,11 @@ describe("Permission Checker", () => {
|
|||
|
||||
it("should use default policies when no custom permissions provided", () => {
|
||||
const result = checkToolPermission({
|
||||
name: "readFile",
|
||||
name: "read_file",
|
||||
arguments: { path: "/test.txt" },
|
||||
});
|
||||
|
||||
// Should match the default policies (readFile should be "allow")
|
||||
// Should match the default policies (read_file should be "allow")
|
||||
expect(result.permission).toBe("allow");
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
import { getServiceSync } from "../services/index.js";
|
||||
import { SERVICE_NAMES } from "../services/types.js";
|
||||
import type { ToolPermissionServiceState } from "../services/types.js";
|
||||
import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
|
||||
import {
|
||||
PermissionCheckResult,
|
||||
|
|
@ -54,7 +57,20 @@ export function checkToolPermission(
|
|||
toolCall: ToolCallRequest,
|
||||
permissions?: ToolPermissions
|
||||
): PermissionCheckResult {
|
||||
const policies = permissions?.policies || DEFAULT_TOOL_POLICIES;
|
||||
// Get permissions from service if not provided
|
||||
let policies = permissions?.policies;
|
||||
|
||||
if (!policies) {
|
||||
try {
|
||||
const serviceResult = getServiceSync<ToolPermissionServiceState>(
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS
|
||||
);
|
||||
policies = serviceResult.value?.permissions.policies || DEFAULT_TOOL_POLICIES;
|
||||
} catch {
|
||||
// Service not initialized yet, use defaults
|
||||
policies = DEFAULT_TOOL_POLICIES;
|
||||
}
|
||||
}
|
||||
|
||||
for (const policy of policies) {
|
||||
if (
|
||||
|
|
|
|||
57
src/permissions/toolNameMapping.ts
Normal file
57
src/permissions/toolNameMapping.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
/**
|
||||
* Maps common display names and variations to actual tool names
|
||||
*/
|
||||
const TOOL_NAME_MAPPINGS: Record<string, string> = {
|
||||
// Display name mappings
|
||||
"Read": "read_file",
|
||||
"Write": "write_file",
|
||||
"List": "list_files",
|
||||
"Search": "search_code",
|
||||
"Bash": "run_terminal_command",
|
||||
"Terminal": "run_terminal_command",
|
||||
"Fetch": "fetch",
|
||||
"Exit": "exit",
|
||||
"Diff": "view_diff",
|
||||
|
||||
// Common variations (case insensitive)
|
||||
"read": "read_file",
|
||||
"write": "write_file",
|
||||
"list": "list_files",
|
||||
"search": "search_code",
|
||||
"bash": "run_terminal_command",
|
||||
"terminal": "run_terminal_command",
|
||||
"cmd": "run_terminal_command",
|
||||
"command": "run_terminal_command",
|
||||
"fetch": "fetch",
|
||||
"exit": "exit",
|
||||
"diff": "view_diff",
|
||||
|
||||
// Actual tool names (passthrough)
|
||||
"read_file": "read_file",
|
||||
"write_file": "write_file",
|
||||
"list_files": "list_files",
|
||||
"search_code": "search_code",
|
||||
"run_terminal_command": "run_terminal_command",
|
||||
"view_diff": "view_diff",
|
||||
};
|
||||
|
||||
/**
|
||||
* Normalizes a tool name from various formats (display name, variations) to the actual tool name
|
||||
*/
|
||||
export function normalizeToolName(input: string): string {
|
||||
// First try exact match (case sensitive)
|
||||
if (TOOL_NAME_MAPPINGS[input]) {
|
||||
return TOOL_NAME_MAPPINGS[input];
|
||||
}
|
||||
|
||||
// Try case insensitive match
|
||||
const lowerInput = input.toLowerCase();
|
||||
for (const [key, value] of Object.entries(TOOL_NAME_MAPPINGS)) {
|
||||
if (key.toLowerCase() === lowerInput) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
// If no mapping found, return as-is (might be an MCP tool or future tool)
|
||||
return input;
|
||||
}
|
||||
86
src/services/ToolPermissionService.integration.test.ts
Normal file
86
src/services/ToolPermissionService.integration.test.ts
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
import { jest } from "@jest/globals";
|
||||
import { DEFAULT_TOOL_POLICIES } from "../permissions/defaultPolicies.js";
|
||||
import { ToolPermissionService } from "./ToolPermissionService.js";
|
||||
|
||||
describe("ToolPermissionService E2E", () => {
|
||||
let service: ToolPermissionService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new ToolPermissionService();
|
||||
});
|
||||
|
||||
it("should handle complete flow from initialization to usage", async () => {
|
||||
// Initialize with overrides
|
||||
const overrides = {
|
||||
allow: ["dangerous_tool"],
|
||||
ask: ["sensitive_tool"],
|
||||
exclude: ["forbidden_tool", "write_*"]
|
||||
};
|
||||
|
||||
const state = await service.initialize(overrides);
|
||||
|
||||
// Verify the compiled policies
|
||||
const policies = state.permissions.policies;
|
||||
|
||||
// Runtime overrides should be first
|
||||
expect(policies[0]).toEqual({ tool: "dangerous_tool", permission: "allow" });
|
||||
expect(policies[1]).toEqual({ tool: "sensitive_tool", permission: "ask" });
|
||||
expect(policies[2]).toEqual({ tool: "forbidden_tool", permission: "exclude" });
|
||||
expect(policies[3]).toEqual({ tool: "write_*", permission: "exclude" });
|
||||
|
||||
// Defaults should follow
|
||||
expect(policies.slice(4)).toEqual(DEFAULT_TOOL_POLICIES);
|
||||
});
|
||||
|
||||
it("should allow dynamic updates after initialization", async () => {
|
||||
// Start with defaults
|
||||
await service.initialize();
|
||||
|
||||
let permissions = service.getPermissions();
|
||||
expect(permissions.policies).toEqual(DEFAULT_TOOL_POLICIES);
|
||||
|
||||
// Update with new policies
|
||||
const newPolicies = [
|
||||
{ tool: "*", permission: "ask" as const } // Ask for everything
|
||||
];
|
||||
|
||||
service.updatePermissions(newPolicies);
|
||||
|
||||
permissions = service.getPermissions();
|
||||
expect(permissions.policies).toEqual(newPolicies);
|
||||
expect(permissions.policies.length).toBe(1);
|
||||
});
|
||||
|
||||
it("should maintain state consistency", async () => {
|
||||
const overrides = {
|
||||
exclude: ["test_tool"]
|
||||
};
|
||||
|
||||
await service.initialize(overrides);
|
||||
|
||||
// Both getState and getPermissions should return same data
|
||||
const state = service.getState();
|
||||
const permissions = service.getPermissions();
|
||||
|
||||
expect(state.permissions).toBe(permissions);
|
||||
expect(state.permissions.policies[0]).toEqual({ tool: "test_tool", permission: "exclude" });
|
||||
});
|
||||
|
||||
it("should handle concurrent access correctly", async () => {
|
||||
// Initialize service
|
||||
await service.initialize({ allow: ["tool1"] });
|
||||
|
||||
// Simulate concurrent reads
|
||||
const promises = Array(10).fill(null).map(() =>
|
||||
Promise.resolve(service.getPermissions())
|
||||
);
|
||||
|
||||
const results = await Promise.all(promises);
|
||||
|
||||
// All should return the same reference
|
||||
const firstResult = results[0];
|
||||
results.forEach(result => {
|
||||
expect(result).toBe(firstResult);
|
||||
});
|
||||
});
|
||||
});
|
||||
173
src/services/ToolPermissionService.test.ts
Normal file
173
src/services/ToolPermissionService.test.ts
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
import { DEFAULT_TOOL_POLICIES } from "../permissions/defaultPolicies.js";
|
||||
import { ToolPermissionPolicy } from "../permissions/types.js";
|
||||
import { ToolPermissionService } from "./ToolPermissionService.js";
|
||||
|
||||
describe("ToolPermissionService", () => {
|
||||
let service: ToolPermissionService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new ToolPermissionService();
|
||||
});
|
||||
|
||||
describe("initialization", () => {
|
||||
it("should initialize with default policies when no overrides provided", async () => {
|
||||
const state = await service.initialize();
|
||||
|
||||
expect(state.permissions.policies).toEqual(DEFAULT_TOOL_POLICIES);
|
||||
expect(state.permissions.policies.length).toBe(DEFAULT_TOOL_POLICIES.length);
|
||||
});
|
||||
|
||||
it("should prepend runtime overrides to default policies", async () => {
|
||||
const overrides = {
|
||||
allow: ["TestTool1"],
|
||||
ask: ["TestTool2"],
|
||||
exclude: ["TestTool3"]
|
||||
};
|
||||
|
||||
const state = await service.initialize(overrides);
|
||||
const policies = state.permissions.policies;
|
||||
|
||||
// Check that overrides are at the beginning
|
||||
expect(policies[0]).toEqual({ tool: "TestTool1", permission: "allow" });
|
||||
expect(policies[1]).toEqual({ tool: "TestTool2", permission: "ask" });
|
||||
expect(policies[2]).toEqual({ tool: "TestTool3", permission: "exclude" });
|
||||
|
||||
// Check that defaults follow
|
||||
expect(policies.slice(3)).toEqual(DEFAULT_TOOL_POLICIES);
|
||||
});
|
||||
|
||||
it("should handle empty override arrays", async () => {
|
||||
const overrides = {
|
||||
allow: [],
|
||||
ask: [],
|
||||
exclude: []
|
||||
};
|
||||
|
||||
const state = await service.initialize(overrides);
|
||||
|
||||
expect(state.permissions.policies).toEqual(DEFAULT_TOOL_POLICIES);
|
||||
});
|
||||
|
||||
it("should handle partial overrides", async () => {
|
||||
const overrides = {
|
||||
allow: ["OnlyAllowTool"]
|
||||
// ask and exclude are undefined
|
||||
};
|
||||
|
||||
const state = await service.initialize(overrides);
|
||||
const policies = state.permissions.policies;
|
||||
|
||||
expect(policies[0]).toEqual({ tool: "OnlyAllowTool", permission: "allow" });
|
||||
expect(policies.slice(1)).toEqual(DEFAULT_TOOL_POLICIES);
|
||||
});
|
||||
|
||||
it("should handle multiple tools in same override category", async () => {
|
||||
const overrides = {
|
||||
exclude: ["Tool1", "Tool2", "Tool3"]
|
||||
};
|
||||
|
||||
const state = await service.initialize(overrides);
|
||||
const policies = state.permissions.policies;
|
||||
|
||||
expect(policies[0]).toEqual({ tool: "Tool1", permission: "exclude" });
|
||||
expect(policies[1]).toEqual({ tool: "Tool2", permission: "exclude" });
|
||||
expect(policies[2]).toEqual({ tool: "Tool3", permission: "exclude" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("getState", () => {
|
||||
it("should return current state after initialization", async () => {
|
||||
await service.initialize();
|
||||
const state = service.getState();
|
||||
|
||||
expect(state).toBeDefined();
|
||||
expect(state.permissions).toBeDefined();
|
||||
expect(state.permissions.policies).toEqual(DEFAULT_TOOL_POLICIES);
|
||||
});
|
||||
|
||||
it("should return state with overrides", async () => {
|
||||
const overrides = {
|
||||
allow: ["TestTool"]
|
||||
};
|
||||
|
||||
await service.initialize(overrides);
|
||||
const state = service.getState();
|
||||
|
||||
expect(state.permissions.policies[0]).toEqual({ tool: "TestTool", permission: "allow" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("getPermissions", () => {
|
||||
it("should return permissions object", async () => {
|
||||
await service.initialize();
|
||||
const permissions = service.getPermissions();
|
||||
|
||||
expect(permissions).toBeDefined();
|
||||
expect(permissions.policies).toEqual(DEFAULT_TOOL_POLICIES);
|
||||
});
|
||||
});
|
||||
|
||||
describe("updatePermissions", () => {
|
||||
it("should replace all policies with new ones", async () => {
|
||||
await service.initialize();
|
||||
|
||||
const newPolicies: ToolPermissionPolicy[] = [
|
||||
{ tool: "NewTool1", permission: "allow" },
|
||||
{ tool: "NewTool2", permission: "ask" }
|
||||
];
|
||||
|
||||
service.updatePermissions(newPolicies);
|
||||
const state = service.getState();
|
||||
|
||||
expect(state.permissions.policies).toEqual(newPolicies);
|
||||
expect(state.permissions.policies.length).toBe(2);
|
||||
});
|
||||
|
||||
it("should handle empty policy updates", () => {
|
||||
service.updatePermissions([]);
|
||||
const state = service.getState();
|
||||
|
||||
expect(state.permissions.policies).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("override precedence", () => {
|
||||
it("should give precedence to runtime overrides over defaults", async () => {
|
||||
// Assuming read_file has a default policy
|
||||
const overrides = {
|
||||
exclude: ["read_file"]
|
||||
};
|
||||
|
||||
const state = await service.initialize(overrides);
|
||||
const policies = state.permissions.policies;
|
||||
|
||||
// The exclude override should come first
|
||||
const readFileOverride = policies.find(p => p.tool === "read_file");
|
||||
expect(readFileOverride).toBeDefined();
|
||||
expect(readFileOverride?.permission).toBe("exclude");
|
||||
|
||||
// Find the index of the override vs any default
|
||||
const overrideIndex = policies.findIndex(p => p.tool === "read_file" && p.permission === "exclude");
|
||||
const defaultIndex = policies.findIndex(p => p.tool === "read_file" && p.permission !== "exclude");
|
||||
|
||||
if (defaultIndex !== -1) {
|
||||
expect(overrideIndex).toBeLessThan(defaultIndex);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("wildcard support", () => {
|
||||
it("should support wildcard patterns in overrides", async () => {
|
||||
const overrides = {
|
||||
allow: ["mcp__*"],
|
||||
exclude: ["write_*"]
|
||||
};
|
||||
|
||||
const state = await service.initialize(overrides);
|
||||
const policies = state.permissions.policies;
|
||||
|
||||
expect(policies[0]).toEqual({ tool: "mcp__*", permission: "allow" });
|
||||
expect(policies[1]).toEqual({ tool: "write_*", permission: "exclude" });
|
||||
});
|
||||
});
|
||||
});
|
||||
93
src/services/ToolPermissionService.ts
Normal file
93
src/services/ToolPermissionService.ts
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
import { DEFAULT_TOOL_POLICIES } from "../permissions/defaultPolicies.js";
|
||||
import { normalizeToolName } from "../permissions/toolNameMapping.js";
|
||||
import { ToolPermissionPolicy, ToolPermissions } from "../permissions/types.js";
|
||||
import logger from "../util/logger.js";
|
||||
|
||||
export interface ToolPermissionServiceState {
|
||||
permissions: ToolPermissions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Service for managing tool permissions with a single source of truth
|
||||
*/
|
||||
export class ToolPermissionService {
|
||||
private state: ToolPermissionServiceState = {
|
||||
permissions: { policies: [...DEFAULT_TOOL_POLICIES] }
|
||||
};
|
||||
|
||||
/**
|
||||
* Initialize the tool permission service with runtime overrides
|
||||
*/
|
||||
async initialize(runtimeOverrides?: {
|
||||
allow?: string[];
|
||||
ask?: string[];
|
||||
exclude?: string[];
|
||||
}): Promise<ToolPermissionServiceState> {
|
||||
logger.debug("Initializing ToolPermissionService");
|
||||
|
||||
// Start with default policies
|
||||
const compiledPolicies: ToolPermissionPolicy[] = [...DEFAULT_TOOL_POLICIES];
|
||||
|
||||
// Apply runtime overrides if provided
|
||||
if (runtimeOverrides) {
|
||||
const overridePolicies: ToolPermissionPolicy[] = [];
|
||||
|
||||
// Convert runtime overrides to policies
|
||||
if (runtimeOverrides.allow) {
|
||||
for (const tool of runtimeOverrides.allow) {
|
||||
const normalizedName = normalizeToolName(tool);
|
||||
overridePolicies.push({ tool: normalizedName, permission: "allow" });
|
||||
}
|
||||
}
|
||||
|
||||
if (runtimeOverrides.ask) {
|
||||
for (const tool of runtimeOverrides.ask) {
|
||||
const normalizedName = normalizeToolName(tool);
|
||||
overridePolicies.push({ tool: normalizedName, permission: "ask" });
|
||||
}
|
||||
}
|
||||
|
||||
if (runtimeOverrides.exclude) {
|
||||
for (const tool of runtimeOverrides.exclude) {
|
||||
const normalizedName = normalizeToolName(tool);
|
||||
overridePolicies.push({ tool: normalizedName, permission: "exclude" });
|
||||
}
|
||||
}
|
||||
|
||||
// Prepend override policies (they take precedence)
|
||||
compiledPolicies.unshift(...overridePolicies);
|
||||
|
||||
logger.debug(`Applied ${overridePolicies.length} runtime permission overrides`);
|
||||
}
|
||||
|
||||
this.state = {
|
||||
permissions: { policies: compiledPolicies }
|
||||
};
|
||||
|
||||
return this.state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current permission state
|
||||
*/
|
||||
getState(): ToolPermissionServiceState {
|
||||
return this.state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the compiled permissions
|
||||
*/
|
||||
getPermissions(): ToolPermissions {
|
||||
return this.state.permissions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update permissions (e.g., when config changes)
|
||||
*/
|
||||
updatePermissions(newPolicies: ToolPermissionPolicy[]) {
|
||||
this.state = {
|
||||
permissions: { policies: newPolicies }
|
||||
};
|
||||
logger.debug(`Updated tool permissions with ${newPolicies.length} policies`);
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ import { ConfigService } from "./ConfigService.js";
|
|||
import { MCPServiceWrapper } from "./MCPServiceWrapper.js";
|
||||
import { ModelService } from "./ModelService.js";
|
||||
import { serviceContainer } from "./ServiceContainer.js";
|
||||
import { ToolPermissionService } from "./ToolPermissionService.js";
|
||||
import {
|
||||
ApiClientServiceState,
|
||||
AuthServiceState,
|
||||
|
|
@ -19,6 +20,7 @@ const configService = new ConfigService();
|
|||
const modelService = new ModelService();
|
||||
const apiClientService = new ApiClientService();
|
||||
const mcpServiceWrapper = new MCPServiceWrapper();
|
||||
const toolPermissionService = new ToolPermissionService();
|
||||
|
||||
/**
|
||||
* Initialize all services and register them with the service container
|
||||
|
|
@ -27,6 +29,12 @@ export async function initializeServices(options: ServiceInitOptions = {}) {
|
|||
logger.debug("Initializing service registry");
|
||||
|
||||
// Register service factories with dependencies
|
||||
serviceContainer.register(
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS,
|
||||
() => toolPermissionService.initialize(options.toolPermissionOverrides),
|
||||
[] // No dependencies - initialize first
|
||||
);
|
||||
|
||||
serviceContainer.register(
|
||||
SERVICE_NAMES.AUTH,
|
||||
() => authService.initialize(),
|
||||
|
|
@ -160,6 +168,7 @@ export function reloadService(serviceName: string) {
|
|||
*/
|
||||
export function areServicesReady(): boolean {
|
||||
return [
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS,
|
||||
SERVICE_NAMES.AUTH,
|
||||
SERVICE_NAMES.API_CLIENT,
|
||||
SERVICE_NAMES.CONFIG,
|
||||
|
|
@ -184,6 +193,7 @@ export const services = {
|
|||
model: modelService,
|
||||
apiClient: apiClientService,
|
||||
mcp: mcpServiceWrapper,
|
||||
toolPermissions: toolPermissionService,
|
||||
} as const;
|
||||
|
||||
// Export the service container for advanced usage
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { BaseLlmApi } from "@continuedev/openai-adapters";
|
|||
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
|
||||
import { AuthConfig } from "../auth/workos.js";
|
||||
import { MCPService } from "../mcp.js";
|
||||
import { ToolPermissions } from "../permissions/types.js";
|
||||
|
||||
/**
|
||||
* Service lifecycle states
|
||||
|
|
@ -56,6 +57,10 @@ export interface ApiClientServiceState {
|
|||
apiClient: DefaultApiInterface | null;
|
||||
}
|
||||
|
||||
export interface ToolPermissionServiceState {
|
||||
permissions: ToolPermissions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Service names as constants to prevent typos
|
||||
*/
|
||||
|
|
@ -64,7 +69,8 @@ export const SERVICE_NAMES = {
|
|||
CONFIG: 'config',
|
||||
MODEL: 'model',
|
||||
MCP: 'mcp',
|
||||
API_CLIENT: 'apiClient'
|
||||
API_CLIENT: 'apiClient',
|
||||
TOOL_PERMISSIONS: 'toolPermissions'
|
||||
} as const;
|
||||
|
||||
/**
|
||||
|
|
@ -74,4 +80,9 @@ export interface ServiceInitOptions {
|
|||
configPath?: string;
|
||||
rules?: string[];
|
||||
headless?: boolean;
|
||||
toolPermissionOverrides?: {
|
||||
allow?: string[];
|
||||
ask?: string[];
|
||||
exclude?: string[];
|
||||
};
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import { Box, Text, useInput } from "ink";
|
||||
import React, { useState } from "react";
|
||||
import { getToolDisplayName } from "../../tools.js";
|
||||
import { ToolPreview, DetailedToolPreview } from "./ToolPreview.js";
|
||||
|
||||
interface PermissionOption {
|
||||
id: string;
|
||||
|
|
@ -91,6 +92,14 @@ export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
|
|||
{displayName}({formattedArgs})
|
||||
</Text>
|
||||
|
||||
{/* Show preview of what the tool will do */}
|
||||
<Box marginTop={1}>
|
||||
<ToolPreview toolName={toolName} toolArgs={toolArgs} />
|
||||
</Box>
|
||||
|
||||
{/* Show detailed preview if available */}
|
||||
<DetailedToolPreview toolName={toolName} toolArgs={toolArgs} />
|
||||
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text color="dim">Would you like to continue?</Text>
|
||||
{PERMISSION_OPTIONS.map((option, index) => {
|
||||
|
|
|
|||
173
src/ui/components/ToolPreview.tsx
Normal file
173
src/ui/components/ToolPreview.tsx
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
import { Box, Text } from "ink";
|
||||
import * as fs from "fs";
|
||||
import path from "path";
|
||||
import React from "react";
|
||||
import { createTwoFilesPatch } from "diff";
|
||||
import { getToolDisplayName } from "../../tools.js";
|
||||
import { ColoredDiff } from "../ColoredDiff.js";
|
||||
|
||||
interface ToolPreviewProps {
|
||||
toolName: string;
|
||||
toolArgs: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a preview of what a tool will do based on its arguments
|
||||
*/
|
||||
export const ToolPreview: React.FC<ToolPreviewProps> = ({ toolName, toolArgs }) => {
|
||||
const formatPath = (filePath: string) => {
|
||||
if (path.isAbsolute(filePath)) {
|
||||
const workspaceRoot = process.cwd();
|
||||
const relativePath = path.relative(workspaceRoot, filePath);
|
||||
return relativePath || filePath;
|
||||
}
|
||||
return filePath;
|
||||
};
|
||||
|
||||
const getPreview = () => {
|
||||
switch (toolName) {
|
||||
case "read_file":
|
||||
if (toolArgs.filepath) {
|
||||
return `Will read: ${formatPath(toolArgs.filepath)}`;
|
||||
}
|
||||
return "Will read a file";
|
||||
|
||||
case "write_file":
|
||||
if (toolArgs.filepath) {
|
||||
const exists = fs.existsSync(toolArgs.filepath);
|
||||
const action = exists ? "modify" : "create";
|
||||
return `Will ${action}: ${formatPath(toolArgs.filepath)}`;
|
||||
}
|
||||
return "Will write to a file";
|
||||
|
||||
case "edit_file":
|
||||
if (toolArgs.filepath) {
|
||||
return `Will edit: ${formatPath(toolArgs.filepath)}`;
|
||||
}
|
||||
return "Will edit a file";
|
||||
|
||||
case "list_files":
|
||||
if (toolArgs.directory) {
|
||||
return `Will list files in: ${formatPath(toolArgs.directory)}`;
|
||||
}
|
||||
return "Will list files in current directory";
|
||||
|
||||
case "search_code":
|
||||
if (toolArgs.pattern) {
|
||||
const truncatedPattern = toolArgs.pattern.length > 50
|
||||
? toolArgs.pattern.substring(0, 50) + "..."
|
||||
: toolArgs.pattern;
|
||||
return `Will search for: "${truncatedPattern}"`;
|
||||
}
|
||||
return "Will search the codebase";
|
||||
|
||||
case "run_terminal_command":
|
||||
if (toolArgs.command) {
|
||||
const truncatedCmd = toolArgs.command.length > 60
|
||||
? toolArgs.command.substring(0, 60) + "..."
|
||||
: toolArgs.command;
|
||||
return `Will run: ${truncatedCmd}`;
|
||||
}
|
||||
return "Will run a terminal command";
|
||||
|
||||
case "fetch":
|
||||
if (toolArgs.url) {
|
||||
return `Will fetch: ${toolArgs.url}`;
|
||||
}
|
||||
return "Will fetch from a URL";
|
||||
|
||||
case "view_diff":
|
||||
return "Will show git diff";
|
||||
|
||||
default:
|
||||
// For unknown tools, show what args will be passed
|
||||
const argCount = Object.keys(toolArgs || {}).length;
|
||||
if (argCount > 0) {
|
||||
return `Will call ${getToolDisplayName(toolName)} with ${argCount} argument${argCount !== 1 ? 's' : ''}`;
|
||||
}
|
||||
return `Will call ${getToolDisplayName(toolName)}`;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Text color="gray">⎿ </Text>
|
||||
<Text color="gray">{getPreview()}</Text>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Shows a detailed preview for tools where we can predict the output
|
||||
*/
|
||||
export const DetailedToolPreview: React.FC<ToolPreviewProps> = ({ toolName, toolArgs }) => {
|
||||
// For edit operations, we could show a diff preview if we have old_string/new_string
|
||||
if (toolName === "edit_file" && toolArgs.old_string && toolArgs.new_string) {
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Text color="gray">Preview of changes:</Text>
|
||||
<Box flexDirection="column" paddingLeft={2}>
|
||||
<Text color="red">- {toolArgs.old_string.split('\n')[0]}</Text>
|
||||
<Text color="green">+ {toolArgs.new_string.split('\n')[0]}</Text>
|
||||
{(toolArgs.old_string.split('\n').length > 1 || toolArgs.new_string.split('\n').length > 1) &&
|
||||
<Text color="gray"> ...</Text>
|
||||
}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// For write operations, show diff preview if file exists
|
||||
if (toolName === "write_file" && toolArgs.filepath && toolArgs.content) {
|
||||
try {
|
||||
if (fs.existsSync(toolArgs.filepath)) {
|
||||
const oldContent = fs.readFileSync(toolArgs.filepath, "utf-8");
|
||||
const newContent = toolArgs.content;
|
||||
|
||||
// Generate a diff preview
|
||||
const diff = createTwoFilesPatch(
|
||||
toolArgs.filepath,
|
||||
toolArgs.filepath,
|
||||
oldContent,
|
||||
newContent,
|
||||
undefined,
|
||||
undefined,
|
||||
{ context: 2 }
|
||||
);
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Text color="gray">Preview of changes:</Text>
|
||||
<ColoredDiff diffContent={diff} />
|
||||
</Box>
|
||||
);
|
||||
} else {
|
||||
// New file - show content preview
|
||||
const lines = toolArgs.content.split('\n');
|
||||
const preview = lines.slice(0, 3);
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Text color="gray">New file content:</Text>
|
||||
<Box flexDirection="column" paddingLeft={2}>
|
||||
{preview.map((line: string, i: number) => (
|
||||
<Text key={i} color="green">{line || ' '}</Text>
|
||||
))}
|
||||
{lines.length > 3 && <Text color="gray">... ({lines.length - 3} more lines)</Text>}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
// If we can't read the file, just show a simple preview
|
||||
const lines = toolArgs.content.split('\n');
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Text color="gray">Content preview ({lines.length} lines)</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
|
@ -10,13 +10,19 @@ export async function startTUIChat(
|
|||
initialPrompt?: string,
|
||||
resume?: boolean,
|
||||
configPath?: string,
|
||||
additionalRules?: string[]
|
||||
additionalRules?: string[],
|
||||
toolPermissionOverrides?: {
|
||||
allow?: string[];
|
||||
ask?: string[];
|
||||
exclude?: string[];
|
||||
}
|
||||
) {
|
||||
// Initialize services in the background - TUI will show loading states
|
||||
initializeServices({
|
||||
configPath,
|
||||
rules: additionalRules,
|
||||
headless: false,
|
||||
toolPermissionOverrides,
|
||||
}).catch((error) => {
|
||||
console.error("Failed to initialize services:", error);
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue