From 67652de55b7958a8a0cd3a361971606eeb805d9d Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 26 Jul 2025 19:37:54 -0700 Subject: [PATCH] address PR feedback --- src/commands/serve.ts | 51 +++++++------- src/permissions/permissionChecker.test.ts | 18 +++++ src/permissions/permissionChecker.ts | 7 +- src/streamChatResponse.ts | 68 ++++++++++--------- .../components/ToolPermissionRequest.test.tsx | 18 ++--- 5 files changed, 94 insertions(+), 68 deletions(-) diff --git a/src/commands/serve.ts b/src/commands/serve.ts index c48a1afd5..d1d404364 100644 --- a/src/commands/serve.ts +++ b/src/commands/serve.ts @@ -5,15 +5,12 @@ import type { ChatCompletionMessageParam } from "openai/resources.mjs"; import path from "path"; import { promisify } from "util"; import { - ensureOrganization, getAssistantSlug, - getOrganizationId, - loadAuthConfig, } from "../auth/workos.js"; -import { runNormalFlow } from "../onboarding.js"; import { toolPermissionManager } from "../permissions/permissionManager.js"; import { saveSession } from "../session.js"; -import { initializeServices } from "../services/index.js"; +import { getService, initializeServices, SERVICE_NAMES } from "../services/index.js"; +import { AuthServiceState, ConfigServiceState, ModelServiceState } from "../services/types.js"; import { streamChatResponse, type StreamCallbacks } from "../streamChatResponse.js"; import { constructSystemMessage } from "../systemMessage.js"; import telemetryService from "../telemetry/telemetryService.js"; @@ -37,6 +34,7 @@ interface PendingPermission { timestamp: number; } + interface ServerState { chatHistory: ChatCompletionMessageParam[]; displayMessages: DisplayMessage[]; // Messages formatted for display with tool info @@ -63,34 +61,37 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { ask: options.ask, exclude: options.exclude, }, + configPath: options.config, + rules: options.rule, + headless: true, // Skip onboarding in serve mode }); - // Initialize authentication - const authConfig = loadAuthConfig(); + // Get initialized services from the service container + const [configState, modelState] = await Promise.all([ + getService(SERVICE_NAMES.CONFIG), + getService(SERVICE_NAMES.MODEL), + ]); - // Initialize with normal flow (skip onboarding like headless mode) - const { config, llmApi, model } = await runNormalFlow( - authConfig, - options.config, - options.rule - ); + if (!configState.config || !modelState.llmApi || !modelState.model) { + throw new Error("Failed to initialize required services"); + } - // Ensure organization is selected if authenticated - let finalAuthConfig = authConfig; - if (config && authConfig) { - finalAuthConfig = await ensureOrganization(authConfig, true); // headless mode - if (finalAuthConfig) { - const organizationId = getOrganizationId(finalAuthConfig); - if (organizationId) { - telemetryService.updateOrganization(organizationId); - } - } + const { config, llmApi, model } = { + config: configState.config, + llmApi: modelState.llmApi, + model: modelState.model, + }; + + // Organization selection is already handled in initializeServices + const authState = await getService(SERVICE_NAMES.AUTH); + if (authState.organizationId) { + telemetryService.updateOrganization(authState.organizationId); } // Log configuration information - const organizationId = getOrganizationId(finalAuthConfig || authConfig) || 'personal'; + const organizationId = authState.organizationId || 'personal'; const assistantName = config.name; - const assistantSlug = getAssistantSlug(finalAuthConfig || authConfig); + const assistantSlug = getAssistantSlug(authState.authConfig); const modelProvider = model.provider; const modelName = model.model; diff --git a/src/permissions/permissionChecker.test.ts b/src/permissions/permissionChecker.test.ts index 7baf041de..ba84b725f 100644 --- a/src/permissions/permissionChecker.test.ts +++ b/src/permissions/permissionChecker.test.ts @@ -47,6 +47,24 @@ describe("Permission Checker", () => { expect(matchesToolPattern("test.file", "test.file")).toBe(true); expect(matchesToolPattern("test_file", "test.file")).toBe(false); expect(matchesToolPattern("test[file]", "test[file]")).toBe(true); + expect(matchesToolPattern("testa", "test[abc]")).toBe(false); + expect(matchesToolPattern("test[abc]", "test[abc]")).toBe(true); + expect(matchesToolPattern("test(abc)", "test(abc)")).toBe(true); + expect(matchesToolPattern("test+plus", "test+plus")).toBe(true); + expect(matchesToolPattern("test^caret", "test^caret")).toBe(true); + 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); + }); + + it("should handle wildcard patterns with special regex characters", () => { + expect(matchesToolPattern("test[abc].txt", "test[abc].*")).toBe(true); + expect(matchesToolPattern("test[abc]_file", "test[abc].*")).toBe(false); + expect(matchesToolPattern("mcp__tool[1]", "mcp__*")).toBe(true); + expect(matchesToolPattern("file.test.txt", "*.test.*")).toBe(true); + expect(matchesToolPattern("(tool)_name", "(tool)*")).toBe(true); + expect(matchesToolPattern("tool+plus_extra", "tool+plus*")).toBe(true); }); }); diff --git a/src/permissions/permissionChecker.ts b/src/permissions/permissionChecker.ts index e87e8a65b..8a4cbf9b2 100644 --- a/src/permissions/permissionChecker.ts +++ b/src/permissions/permissionChecker.ts @@ -17,8 +17,11 @@ export function matchesToolPattern(toolName: string, pattern: string): boolean { if (pattern === toolName) return true; // Handle wildcard patterns like "mcp__*" - if (pattern.includes("*")) { - const regexPattern = pattern.replace(/\*/g, ".*").replace(/\?/g, "."); + if (pattern.includes("*") || pattern.includes("?")) { + // 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}$`); return regex.test(toolName); } diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index 0ae778660..e270b73d1 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -467,38 +467,42 @@ export async function streamChatResponse( } else if (permissionCheck.permission === "ask") { // Request permission from user if (callbacks?.onToolPermissionRequest) { - // Create a promise that resolves when permission is granted/denied - const permissionPromise = new Promise((resolve) => { - const requestId = `tool-request-${toolCall.id}`; - - // Set up listener for permission response - const handlePermissionResponse = (result: { - requestId: string; - approved: boolean; - }) => { - if (result.requestId === requestId) { - toolPermissionManager.off( - "permissionResponse", - handlePermissionResponse - ); - resolve(result.approved); - } - }; - - toolPermissionManager.on( - "permissionResponse", - handlePermissionResponse - ); - - // Notify UI about permission request - callbacks.onToolPermissionRequest!( - toolCall.name, - toolCall.arguments, - requestId - ); - }); - - approved = await permissionPromise; + // Use the proper toolPermissionManager API + const toolCallRequest = { + name: toolCall.name, + arguments: toolCall.arguments, + }; + + // Set up listener for permissionRequested event + const handlePermissionRequested = (event: { + requestId: string; + toolCall: { name: string; arguments: any }; + }) => { + if (event.toolCall.name === toolCall.name) { + toolPermissionManager.off( + "permissionRequested", + handlePermissionRequested + ); + // Notify UI about permission request + callbacks.onToolPermissionRequest!( + event.toolCall.name, + event.toolCall.arguments, + event.requestId + ); + } + }; + + toolPermissionManager.on( + "permissionRequested", + handlePermissionRequested + ); + + // Request permission using the proper API + const permissionResult = await toolPermissionManager.requestPermission( + toolCallRequest + ); + + approved = permissionResult.approved; } else { // Fallback: deny if no UI callback available approved = false; diff --git a/src/ui/components/ToolPermissionRequest.test.tsx b/src/ui/components/ToolPermissionRequest.test.tsx index 1f7f9bf76..3d8a2559d 100644 --- a/src/ui/components/ToolPermissionRequest.test.tsx +++ b/src/ui/components/ToolPermissionRequest.test.tsx @@ -9,8 +9,8 @@ function formatArgs(args: any): string { const firstKey = Object.keys(args)[0]; const firstValue = args[firstKey]; - if (typeof firstValue === "string" && firstValue.length > 50) { - return `${firstValue.substring(0, 50)}...`; + if (typeof firstValue === "string" && firstValue.length > 60) { + return `${firstValue.substring(0, 60)}...`; } return String(firstValue); @@ -34,8 +34,8 @@ describe("formatArgs function", () => { it("should truncate long strings", () => { const longString = "a".repeat(100); const result = formatArgs({ content: longString }); - expect(result).toBe("a".repeat(50) + "..."); - expect(result.length).toBe(53); // 50 chars + "..." + expect(result).toBe("a".repeat(60) + "..."); + expect(result.length).toBe(63); // 60 chars + "..." }); it("should not truncate short strings", () => { @@ -45,17 +45,17 @@ describe("formatArgs function", () => { expect(result).not.toContain("..."); }); - it("should handle exactly 50 character strings", () => { - const exactString = "a".repeat(50); + it("should handle exactly 60 character strings", () => { + const exactString = "a".repeat(60); const result = formatArgs({ content: exactString }); expect(result).toBe(exactString); expect(result).not.toContain("..."); }); - it("should handle 51 character strings", () => { - const slightlyLongString = "a".repeat(51); + it("should handle 61 character strings", () => { + const slightlyLongString = "a".repeat(61); const result = formatArgs({ content: slightlyLongString }); - expect(result).toBe("a".repeat(50) + "..."); + expect(result).toBe("a".repeat(60) + "..."); }); it("should use first key when multiple arguments", () => {