fix tool permissions bug

This commit is contained in:
Nate 2025-08-03 19:19:46 -04:00
parent 52cefcfa02
commit 889421049f
9 changed files with 351 additions and 161 deletions

View file

@ -1,8 +1,8 @@
import {
checkToolPermission,
filterExcludedTools,
matchesToolPattern,
matchesArguments,
matchesToolPattern,
} from "./permissionChecker.js";
import { ToolPermissions } from "./types.js";
@ -20,7 +20,9 @@ describe("Permission Checker", () => {
});
it("should match prefix wildcards", () => {
expect(matchesToolPattern("mcp__ide__getDiagnostics", "mcp__*")).toBe(true);
expect(matchesToolPattern("mcp__ide__getDiagnostics", "mcp__*")).toBe(
true
);
expect(matchesToolPattern("mcp__filesystem__read", "mcp__*")).toBe(true);
expect(matchesToolPattern("builtin__readFile", "mcp__*")).toBe(false);
});
@ -55,7 +57,9 @@ describe("Permission Checker", () => {
expect(matchesToolPattern("test$dollar", "test$dollar")).toBe(true);
expect(matchesToolPattern("test{brace}", "test{brace}")).toBe(true);
expect(matchesToolPattern("test|pipe", "test|pipe")).toBe(true);
expect(matchesToolPattern("test\\backslash", "test\\backslash")).toBe(true);
expect(matchesToolPattern("test\\backslash", "test\\backslash")).toBe(
true
);
});
it("should handle wildcard patterns with special regex characters", () => {
@ -69,36 +73,66 @@ describe("Permission Checker", () => {
describe("Bash command patterns", () => {
it("should match Bash command patterns with Bash tool", () => {
expect(matchesToolPattern("Bash", "Bash(ls*)", { command: "ls" })).toBe(true);
expect(matchesToolPattern("Bash", "Bash(ls*)", { command: "ls -la" })).toBe(true);
expect(matchesToolPattern("Bash", "Bash(ls*)", { command: "pwd" })).toBe(false);
expect(matchesToolPattern("Bash", "Bash(ls*)", { command: "ls" })).toBe(
true
);
expect(
matchesToolPattern("Bash", "Bash(ls*)", { command: "ls -la" })
).toBe(true);
expect(
matchesToolPattern("Bash", "Bash(ls*)", { command: "pwd" })
).toBe(false);
});
it("should match Bash command patterns with Bash display name", () => {
expect(matchesToolPattern("Bash", "Bash(git*)", { command: "git status" })).toBe(true);
expect(matchesToolPattern("Bash", "Bash(git*)", { command: "git commit" })).toBe(true);
expect(matchesToolPattern("Bash", "Bash(git*)", { command: "npm install" })).toBe(false);
expect(
matchesToolPattern("Bash", "Bash(git*)", { command: "git status" })
).toBe(true);
expect(
matchesToolPattern("Bash", "Bash(git*)", { command: "git commit" })
).toBe(true);
expect(
matchesToolPattern("Bash", "Bash(git*)", { command: "npm install" })
).toBe(false);
});
it("should match exact Bash commands", () => {
expect(matchesToolPattern("Bash", "Bash(ls)", { command: "ls" })).toBe(true);
expect(matchesToolPattern("Bash", "Bash(ls)", { command: "ls -la" })).toBe(false);
expect(matchesToolPattern("Bash", "Bash(ls)", { command: "ls" })).toBe(
true
);
expect(
matchesToolPattern("Bash", "Bash(ls)", { command: "ls -la" })
).toBe(false);
});
it("should not match Bash patterns for non-bash tools", () => {
expect(matchesToolPattern("Read", "Bash(ls*)", { command: "ls" })).toBe(false);
expect(matchesToolPattern("Write", "Bash(git*)", { command: "git status" })).toBe(false);
expect(matchesToolPattern("Read", "Bash(ls*)", { command: "ls" })).toBe(
false
);
expect(
matchesToolPattern("Write", "Bash(git*)", { command: "git status" })
).toBe(false);
});
it("should not match Bash patterns without command argument", () => {
expect(matchesToolPattern("Bash", "Bash(ls*)", {})).toBe(false);
expect(matchesToolPattern("Bash", "Bash(ls*)", { other: "value" })).toBe(false);
expect(
matchesToolPattern("Bash", "Bash(ls*)", { other: "value" })
).toBe(false);
});
it("should handle complex Bash command patterns", () => {
expect(matchesToolPattern("Bash", "Bash(npm*)", { command: "npm install" })).toBe(true);
expect(matchesToolPattern("Bash", "Bash(npm*)", { command: "npm run build" })).toBe(true);
expect(matchesToolPattern("Bash", "Bash(git*commit*)", { command: "git commit -m 'test'" })).toBe(true);
expect(
matchesToolPattern("Bash", "Bash(npm*)", { command: "npm install" })
).toBe(true);
expect(
matchesToolPattern("Bash", "Bash(npm*)", { command: "npm run build" })
).toBe(true);
expect(
matchesToolPattern("Bash", "Bash(git*commit*)", {
command: "git commit -m 'test'",
})
).toBe(true);
});
});
});
@ -114,7 +148,7 @@ describe("Permission Checker", () => {
const args = { path: "/test.txt", mode: "read" };
const patterns = { path: "/test.txt" };
expect(matchesArguments(args, patterns)).toBe(true);
const nonMatchingPatterns = { path: "/other.txt" };
expect(matchesArguments(args, nonMatchingPatterns)).toBe(false);
});
@ -123,7 +157,7 @@ describe("Permission Checker", () => {
const args = { path: "/any/file.txt", mode: "write" };
const patterns = { path: "*", mode: "write" };
expect(matchesArguments(args, patterns)).toBe(true);
const wildcardOnlyPatterns = { path: "*" };
expect(matchesArguments(args, wildcardOnlyPatterns)).toBe(true);
});
@ -132,7 +166,7 @@ describe("Permission Checker", () => {
const args = { path: "/test.txt", mode: "read", format: "json" };
const allMatchingPatterns = { path: "/test.txt", mode: "read" };
expect(matchesArguments(args, allMatchingPatterns)).toBe(true);
const partialMatchingPatterns = { path: "/test.txt", mode: "write" };
expect(matchesArguments(args, partialMatchingPatterns)).toBe(false);
});
@ -147,7 +181,7 @@ describe("Permission Checker", () => {
const args = { count: 42, enabled: true, data: null, list: [1, 2, 3] };
const patterns = { count: 42, enabled: true };
expect(matchesArguments(args, patterns)).toBe(true);
const mismatchedPatterns = { count: "42" }; // string vs number
expect(matchesArguments(args, mismatchedPatterns)).toBe(false);
});
@ -155,38 +189,43 @@ describe("Permission Checker", () => {
it("should handle complex object arguments with reference equality", () => {
const configObj = { host: "localhost", port: 3000 };
const optionsArray = ["verbose", "debug"];
const args = {
const args = {
config: configObj,
options: optionsArray
options: optionsArray,
};
const patterns = {
const patterns = {
config: configObj, // Same reference
options: optionsArray // Same reference
options: optionsArray, // Same reference
};
expect(matchesArguments(args, patterns)).toBe(true);
const differentObjectPatterns = {
config: { host: "localhost", port: 8080 } // Different object
const differentObjectPatterns = {
config: { host: "localhost", port: 8080 }, // Different object
};
expect(matchesArguments(args, differentObjectPatterns)).toBe(false);
const differentButEqualObjectPatterns = {
config: { host: "localhost", port: 3000 } // Different reference, same content
const differentButEqualObjectPatterns = {
config: { host: "localhost", port: 3000 }, // Different reference, same content
};
expect(matchesArguments(args, differentButEqualObjectPatterns)).toBe(false);
expect(matchesArguments(args, differentButEqualObjectPatterns)).toBe(
false
);
});
describe("glob pattern matching", () => {
it("should match glob patterns with asterisk wildcards", () => {
const args = { command: "cd ../projects && ls", file_path: "/src/file.ts" };
const args = {
command: "cd ../projects && ls",
file_path: "/src/file.ts",
};
// Test command patterns
expect(matchesArguments(args, { command: "cd*" })).toBe(true);
expect(matchesArguments(args, { command: "*ls" })).toBe(true);
expect(matchesArguments(args, { command: "*&&*" })).toBe(true);
expect(matchesArguments(args, { command: "pwd*" })).toBe(false);
// Test file path patterns
expect(matchesArguments(args, { file_path: "*.ts" })).toBe(true);
expect(matchesArguments(args, { file_path: "/src/*" })).toBe(true);
@ -196,7 +235,7 @@ describe("Permission Checker", () => {
it("should match glob patterns with question mark wildcards", () => {
const args = { command: "git add", file: "test1.js" };
expect(matchesArguments(args, { command: "git a?d" })).toBe(true);
expect(matchesArguments(args, { command: "git a??d" })).toBe(false);
expect(matchesArguments(args, { file: "test?.js" })).toBe(true);
@ -204,87 +243,99 @@ describe("Permission Checker", () => {
});
it("should match complex glob patterns", () => {
const args = {
const args = {
command: "npm run test:unit",
path: "/home/user/projects/myapp/src/utils/helper.ts"
path: "/home/user/projects/myapp/src/utils/helper.ts",
};
expect(matchesArguments(args, { command: "npm * test:*" })).toBe(true);
expect(matchesArguments(args, { command: "npm run *:unit" })).toBe(true);
expect(matchesArguments(args, { command: "npm run *:unit" })).toBe(
true
);
expect(matchesArguments(args, { path: "**/src/**/*.ts" })).toBe(true);
expect(matchesArguments(args, { path: "/home/*/projects/*/src/**" })).toBe(true);
expect(
matchesArguments(args, { path: "/home/*/projects/*/src/**" })
).toBe(true);
expect(matchesArguments(args, { command: "yarn *" })).toBe(false);
});
it("should escape special regex characters in glob patterns", () => {
const args = {
const args = {
command: "echo 'test.pattern'",
regex: "test[0-9]+",
special: "file(1).txt"
special: "file(1).txt",
};
// Literal dots, brackets, parentheses should match exactly
expect(matchesArguments(args, { command: "*'test.pattern'*" })).toBe(true);
expect(matchesArguments(args, { command: "*'test.pattern'*" })).toBe(
true
);
expect(matchesArguments(args, { regex: "test[0-9]+" })).toBe(true);
expect(matchesArguments(args, { special: "file(1).txt" })).toBe(true);
expect(matchesArguments(args, { special: "file(*).txt" })).toBe(true);
// These should not match due to regex escaping
expect(matchesArguments(args, { command: "*test_pattern*" })).toBe(false);
expect(matchesArguments(args, { command: "*test_pattern*" })).toBe(
false
);
expect(matchesArguments(args, { regex: "test*" })).toBe(true); // * is wildcard, + is literal
});
it("should handle mixed exact and glob patterns", () => {
const args = {
tool: "bash",
const args = {
tool: "bash",
command: "cd projects && npm install",
flag: "--verbose"
flag: "--verbose",
};
// Mix of exact and glob matching
expect(matchesArguments(args, {
tool: "bash", // exact match
command: "cd*install", // glob match
flag: "--verbose" // exact match
})).toBe(true);
expect(matchesArguments(args, {
tool: "bash", // exact match
command: "cd*test", // glob no match
flag: "--verbose" // exact match
})).toBe(false);
expect(
matchesArguments(args, {
tool: "bash", // exact match
command: "cd*install", // glob match
flag: "--verbose", // exact match
})
).toBe(true);
expect(
matchesArguments(args, {
tool: "bash", // exact match
command: "cd*test", // glob no match
flag: "--verbose", // exact match
})
).toBe(false);
});
it("should convert non-string values to strings for pattern matching", () => {
const args = {
const args = {
port: 3000,
enabled: true,
count: null,
items: [1, 2, 3]
items: [1, 2, 3],
};
expect(matchesArguments(args, { port: "30*" })).toBe(true);
expect(matchesArguments(args, { enabled: "tr*" })).toBe(true);
expect(matchesArguments(args, { count: "*" })).toBe(true); // null -> ""
expect(matchesArguments(args, { items: "*,*,*" })).toBe(true); // array toString
expect(matchesArguments(args, { port: "40*" })).toBe(false);
expect(matchesArguments(args, { enabled: "fa*" })).toBe(false);
});
it("should handle empty and undefined argument values", () => {
const args = {
const args = {
empty: "",
undef: undefined,
zero: 0,
false_val: false
false_val: false,
};
expect(matchesArguments(args, { empty: "*" })).toBe(true);
expect(matchesArguments(args, { undef: "*" })).toBe(true); // undefined -> ""
expect(matchesArguments(args, { zero: "*" })).toBe(true); // 0 -> "0"
expect(matchesArguments(args, { zero: "*" })).toBe(true); // 0 -> "0"
expect(matchesArguments(args, { false_val: "*" })).toBe(true); // false -> "false"
expect(matchesArguments(args, { empty: "nonempty*" })).toBe(false);
expect(matchesArguments(args, { zero: "1*" })).toBe(false);
});
@ -453,18 +504,18 @@ describe("Permission Checker", () => {
policies: [
{
tool: "Bash",
permission: "exclude",
argumentMatches: { command: "rm*" }
permission: "exclude",
argumentMatches: { command: "rm*" },
},
{
tool: "Write",
permission: "ask",
argumentMatches: { file_path: "**/*.ts" }
argumentMatches: { file_path: "**/*.ts" },
},
{
tool: "Write",
permission: "allow"
}
tool: "Write",
permission: "allow",
},
],
};
@ -478,11 +529,16 @@ describe("Permission Checker", () => {
// Should ask for TypeScript files
const tsResult = checkToolPermission(
{ name: "Write", arguments: { file_path: "/src/components/Button.ts" } },
{
name: "Write",
arguments: { file_path: "/src/components/Button.ts" },
},
permissions
);
expect(tsResult.permission).toBe("ask");
expect(tsResult.matchedPolicy?.argumentMatches?.file_path).toBe("**/*.ts");
expect(tsResult.matchedPolicy?.argumentMatches?.file_path).toBe(
"**/*.ts"
);
// Should allow other file writes
const jsResult = checkToolPermission(

View file

@ -1,6 +1,6 @@
import { getServiceSync } from "../services/index.js";
import { SERVICE_NAMES } from "../services/types.js";
import type { ToolPermissionServiceState } from "../services/types.js";
import { SERVICE_NAMES } from "../services/types.js";
import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
import {
PermissionCheckResult,
@ -14,8 +14,8 @@ import {
* Also handles special Bash command patterns like "Bash(ls*)"
*/
export function matchesToolPattern(
toolName: string,
pattern: string,
toolName: string,
pattern: string,
toolArguments?: Record<string, any>
): boolean {
if (pattern === "*") return true;
@ -29,7 +29,7 @@ export function matchesToolPattern(
if (isBashTool && toolArguments?.command) {
const commandPattern = bashCommandMatch[1];
const command = toolArguments.command;
// Handle command patterns with wildcards
if (commandPattern.includes("*") || commandPattern.includes("?")) {
// Escape all regex metacharacters except * and ?
@ -39,7 +39,7 @@ export function matchesToolPattern(
const regex = new RegExp(`^${regexPattern}$`);
return regex.test(command);
}
// Exact command match
return command === commandPattern;
}
@ -75,16 +75,19 @@ export function matchesArguments(
if (pattern === "*") continue; // Wildcard matches anything
// Handle glob patterns with wildcards (only for string patterns)
if (typeof pattern === "string" && (pattern.includes("*") || pattern.includes("?"))) {
if (
typeof pattern === "string" &&
(pattern.includes("*") || pattern.includes("?"))
) {
// Convert argValue to string for pattern matching
const stringValue = String(argValue ?? "");
// Escape all regex metacharacters except * and ?
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
// Convert * and ? to their regex equivalents
const regexPattern = escaped.replace(/\*/g, ".*").replace(/\?/g, ".");
const regex = new RegExp(`^${regexPattern}$`);
if (!regex.test(stringValue)) {
return false;
}
@ -109,18 +112,19 @@ export function checkToolPermission(
): PermissionCheckResult {
// Get permissions from service if not provided
let policies = permissions?.policies;
if (!policies) {
const serviceResult = getServiceSync<ToolPermissionServiceState>(
SERVICE_NAMES.TOOL_PERMISSIONS
);
// Only use defaults if service is not ready, not registered, or has no value
// This allows critical runtime errors to propagate properly
if (serviceResult.state !== 'ready' || !serviceResult.value) {
if (serviceResult.state !== "ready" || !serviceResult.value) {
policies = DEFAULT_TOOL_POLICIES;
} else {
policies = serviceResult.value.permissions.policies || DEFAULT_TOOL_POLICIES;
policies =
serviceResult.value.permissions.policies || DEFAULT_TOOL_POLICIES;
}
}

View file

@ -28,12 +28,15 @@ export class ServiceContainer extends EventEmitter {
this.factories.set(serviceName, factory);
this.dependencies.set(serviceName, deps);
// Initialize with idle state
this.services.set(serviceName, {
value: null,
state: 'idle',
error: null
});
// Only initialize with idle state if the service doesn't already exist
// This prevents overwriting services that were registered with registerValue
if (!this.services.has(serviceName)) {
this.services.set(serviceName, {
value: null,
state: 'idle',
error: null
});
}
logger.debug(`Registered service: ${serviceName}`, { dependencies: deps });
}
@ -57,7 +60,11 @@ export class ServiceContainer extends EventEmitter {
// Emit ready event
this.emit(`${serviceName}:ready`, value);
logger.debug(`Registered service with immediate value: ${serviceName}`);
logger.debug(`Registered service with immediate value: ${serviceName}`, {
state: 'ready',
hasValue: value !== null,
serviceMapSize: this.services.size
});
}
/**
@ -230,6 +237,29 @@ export class ServiceContainer extends EventEmitter {
return result?.state === 'loading';
}
/**
* Initialize all registered services
* This eagerly loads all services rather than waiting for them to be requested
*/
async initializeAll(): Promise<void> {
logger.debug('Initializing all registered services');
// Get all registered service names
const serviceNames = Array.from(this.factories.keys());
// Load all services in parallel (dependencies will be handled by load())
await Promise.all(
serviceNames.map(name =>
this.load(name).catch(error => {
logger.error(`Failed to initialize service ${name}:`, error);
// Don't throw - let individual services fail without breaking others
})
)
);
logger.debug('All services initialization complete', this.getServiceStates());
}
/**
* Get all service states (for debugging)
*/

View file

@ -260,8 +260,9 @@ describe("ToolPermissionService", () => {
});
describe('isReady()', () => {
test('should return false before initialization', () => {
expect(service.isReady()).toBe(false);
test('should always return true (service is always ready)', () => {
// ToolPermissionService is designed to be always ready since it uses synchronous initialization
expect(service.isReady()).toBe(true);
});
test('should return true after initialization', async () => {

View file

@ -125,6 +125,9 @@ export class ToolPermissionService extends BaseService<ToolPermissionServiceStat
modePolicyCount: modePolicies.length,
});
// Mark as initialized since we're bypassing the async initialize flow
(this as any).isInitialized = true;
return this.getState();
}
@ -253,4 +256,11 @@ export class ToolPermissionService extends BaseService<ToolPermissionServiceStat
isHeadless(): boolean {
return this.currentState.isHeadless;
}
/**
* Override isReady to always return true since we initialize synchronously
*/
override isReady(): boolean {
return true;
}
}

View file

@ -0,0 +1,59 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { initializeServices, getServiceSync, SERVICE_NAMES } from './index.js';
import { serviceContainer } from './ServiceContainer.js';
import type { ToolPermissionServiceState } from './ToolPermissionService.js';
describe('Service Initialization', () => {
beforeEach(() => {
// Clean up service container state
const services = [
SERVICE_NAMES.TOOL_PERMISSIONS,
SERVICE_NAMES.AUTH,
SERVICE_NAMES.API_CLIENT,
SERVICE_NAMES.CONFIG,
SERVICE_NAMES.MODEL,
SERVICE_NAMES.MCP
];
services.forEach(service => {
// Reset service state
(serviceContainer as any).services.delete(service);
(serviceContainer as any).factories.delete(service);
(serviceContainer as any).dependencies.delete(service);
});
});
it('should have TOOL_PERMISSIONS service ready after initialization', async () => {
// Before initialization, service should not be ready
const beforeInit = getServiceSync(SERVICE_NAMES.TOOL_PERMISSIONS);
expect(beforeInit.state).toBe('error'); // Not registered yet
// Initialize services
await initializeServices({
headless: true,
toolPermissionOverrides: {
mode: 'normal'
}
});
// After initialization, service should be ready
const afterInit = getServiceSync<ToolPermissionServiceState>(SERVICE_NAMES.TOOL_PERMISSIONS);
expect(afterInit.state).toBe('ready');
expect(afterInit.value).toBeDefined();
expect(afterInit.value?.currentMode).toBe('normal');
expect(afterInit.value?.isHeadless).toBe(true);
});
it('should have TOOL_PERMISSIONS service ready immediately when accessed early', async () => {
await initializeServices({
headless: true
});
// Simulate early access like in streamChatResponse
const serviceResult = getServiceSync<ToolPermissionServiceState>(SERVICE_NAMES.TOOL_PERMISSIONS);
// Service should be ready, not idle
expect(serviceResult.state).toBe('ready');
expect(serviceResult.value).toBeDefined();
});
});

View file

@ -1,21 +1,21 @@
import { vi } from 'vitest';
import { vi } from "vitest";
import { initializeServices } from './index.js';
import { modeService } from './ModeService.js';
import { initializeServices } from "./index.js";
import { modeService } from "./ModeService.js";
describe('initializeServices', () => {
describe("initializeServices", () => {
let mockModeService: any;
beforeEach(() => {
// Reset all mocks
vi.clearAllMocks();
// Create mock mode service
mockModeService = {
initialize: vi.fn(),
getCurrentMode: vi.fn()
getCurrentMode: vi.fn(),
};
// Set up modeService mock
(modeService as any).initialize = mockModeService.initialize;
(modeService as any).getCurrentMode = mockModeService.getCurrentMode;
@ -25,84 +25,86 @@ describe('initializeServices', () => {
vi.restoreAllMocks();
});
describe('mode conversion', () => {
it('should pass only readonly flag for plan mode', async () => {
describe("mode conversion", () => {
it("should pass only readonly flag for plan mode", async () => {
await initializeServices({
toolPermissionOverrides: {
mode: 'plan',
allow: ['tool1'],
ask: ['tool2'],
exclude: ['tool3']
}
mode: "plan",
allow: ["tool1"],
ask: ["tool2"],
exclude: ["tool3"],
},
});
expect(mockModeService.initialize).toHaveBeenCalledWith({
allow: ['tool1'],
ask: ['tool2'],
exclude: ['tool3'],
readonly: true
allow: ["tool1"],
ask: ["tool2"],
exclude: ["tool3"],
readonly: true,
// auto should NOT be set
});
});
it('should pass only auto flag for auto mode', async () => {
it("should pass only auto flag for auto mode", async () => {
await initializeServices({
toolPermissionOverrides: {
mode: 'auto',
allow: ['tool1'],
ask: ['tool2'],
exclude: ['tool3']
}
mode: "auto",
allow: ["tool1"],
ask: ["tool2"],
exclude: ["tool3"],
},
});
expect(mockModeService.initialize).toHaveBeenCalledWith({
allow: ['tool1'],
ask: ['tool2'],
exclude: ['tool3'],
auto: true
allow: ["tool1"],
ask: ["tool2"],
exclude: ["tool3"],
auto: true,
// readonly should NOT be set
});
});
it('should pass no mode flags for normal mode', async () => {
it("should pass no mode flags for normal mode", async () => {
await initializeServices({
toolPermissionOverrides: {
mode: 'normal',
allow: ['tool1'],
ask: ['tool2'],
exclude: ['tool3']
}
mode: "normal",
allow: ["tool1"],
ask: ["tool2"],
exclude: ["tool3"],
},
});
expect(mockModeService.initialize).toHaveBeenCalledWith({
allow: ['tool1'],
ask: ['tool2'],
exclude: ['tool3']
allow: ["tool1"],
ask: ["tool2"],
exclude: ["tool3"],
// Neither readonly nor auto should be set
});
});
it('should pass no mode flags when mode is undefined', async () => {
it("should pass no mode flags when mode is undefined", async () => {
await initializeServices({
toolPermissionOverrides: {
allow: ['tool1'],
ask: ['tool2'],
exclude: ['tool3']
}
allow: ["tool1"],
ask: ["tool2"],
exclude: ["tool3"],
},
});
expect(mockModeService.initialize).toHaveBeenCalledWith({
allow: ['tool1'],
ask: ['tool2'],
exclude: ['tool3']
allow: ["tool1"],
ask: ["tool2"],
exclude: ["tool3"],
// Neither readonly nor auto should be set
});
});
it('should not call initialize when no toolPermissionOverrides provided', async () => {
it("should call initialize with defaults when no toolPermissionOverrides provided", async () => {
await initializeServices({});
expect(mockModeService.initialize).not.toHaveBeenCalled();
expect(mockModeService.initialize).toHaveBeenCalledWith({
isHeadless: undefined,
});
});
});
});
});

View file

@ -28,6 +28,7 @@ export async function initializeServices(options: ServiceInitOptions = {}) {
logger.debug("Initializing service registry");
// Initialize mode service with tool permission overrides
let modeServiceInitialized = false;
if (options.toolPermissionOverrides) {
const overrides = { ...options.toolPermissionOverrides };
@ -47,18 +48,28 @@ export async function initializeServices(options: ServiceInitOptions = {}) {
}
// If mode is "normal" or undefined, no flags are set
modeService.initialize(initArgs);
await modeService.initialize(initArgs);
modeServiceInitialized = true;
} else {
// Even if no overrides, we need to initialize with defaults
await modeService.initialize({
isHeadless: options.headless
});
modeServiceInitialized = true;
}
// Always register a factory that returns the current state from modeService
// This ensures the service container always has the latest mode state
serviceContainer.register(
// Register the TOOL_PERMISSIONS service with immediate value
// Since ToolPermissionService is already initialized synchronously in ModeService,
// we can register it as a ready value instead of a factory
const toolPermissionState = modeService.getToolPermissionService().getState();
logger.debug("Registering TOOL_PERMISSIONS with state:", {
currentMode: toolPermissionState.currentMode,
isHeadless: toolPermissionState.isHeadless,
policyCount: toolPermissionState.permissions.policies.length
});
serviceContainer.registerValue(
SERVICE_NAMES.TOOL_PERMISSIONS,
async () => {
// Always return the current state from the global mode service
return modeService.getToolPermissionService().getState();
},
[]
toolPermissionState
);
serviceContainer.register(
@ -165,6 +176,10 @@ export async function initializeServices(options: ServiceInitOptions = {}) {
[SERVICE_NAMES.CONFIG] // Depends on config
);
// Eagerly initialize all services to ensure they're ready when needed
// This avoids race conditions and "service not ready" errors
await serviceContainer.initializeAll();
logger.debug("Service registry initialized");
}

View file

@ -48,8 +48,21 @@ export function getAllTools() {
.map((tool) => tool.name) ?? [];
const allToolNames = [...builtinToolNames, ...mcpToolNames];
// Filter out excluded tools based on permissions
const allowedToolNames = filterExcludedTools(allToolNames);
// Check if the ToolPermissionService is ready
const serviceResult = getServiceSync<ToolPermissionServiceState>(
SERVICE_NAMES.TOOL_PERMISSIONS
);
let allowedToolNames: string[];
if (serviceResult.state === 'ready' && serviceResult.value) {
// Filter out excluded tools based on permissions
allowedToolNames = filterExcludedTools(allToolNames);
} else {
// Service not ready - return all tools but log a warning
logger.warn("ToolPermissionService not ready in getAllTools, returning all tools");
allowedToolNames = allToolNames;
}
const allowedToolNamesSet = new Set(allowedToolNames);
// Filter builtin tools