address PR feedback

This commit is contained in:
Nate 2025-07-26 19:37:54 -07:00
parent 62775b9507
commit 67652de55b
5 changed files with 94 additions and 68 deletions

View file

@ -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<ConfigServiceState>(SERVICE_NAMES.CONFIG),
getService<ModelServiceState>(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<AuthServiceState>(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;

View file

@ -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);
});
});

View file

@ -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);
}

View file

@ -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<boolean>((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;

View file

@ -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", () => {