diff --git a/extensions/cli/src/commands/BaseCommandOptions.ts b/extensions/cli/src/commands/BaseCommandOptions.ts index 0d0808ea3..bb32e9a90 100644 --- a/extensions/cli/src/commands/BaseCommandOptions.ts +++ b/extensions/cli/src/commands/BaseCommandOptions.ts @@ -21,6 +21,8 @@ export interface BaseCommandOptions { ask?: string[]; /** Array of tools to exclude from use (--exclude) */ exclude?: string[]; + /** Workflow slug from the hub (--workflow) */ + workflow?: string; } /** diff --git a/extensions/cli/src/configEnhancer.ts b/extensions/cli/src/configEnhancer.ts index ee1c9b254..323d6968d 100644 --- a/extensions/cli/src/configEnhancer.ts +++ b/extensions/cli/src/configEnhancer.ts @@ -7,10 +7,12 @@ import { modelProcessor, processRule, } from "./hubLoader.js"; +import { serviceContainer } from "./services/ServiceContainer.js"; +import { SERVICE_NAMES, WorkflowServiceState } from "./services/types.js"; import { logger } from "./util/logger.js"; /** - * Enhances a configuration by injecting additional components from CLI flags + * Enhances a configuration by injecting additional components from CLI flags and workflow */ export class ConfigEnhancer { /** @@ -22,6 +24,9 @@ export class ConfigEnhancer { ): Promise { let enhancedConfig = { ...config }; + // Apply workflow rules first (highest priority) + enhancedConfig = await this.injectWorkflowRules(enhancedConfig); + // Apply rules if (options.rule && options.rule.length > 0) { enhancedConfig = await this.injectRules(enhancedConfig, options.rule); @@ -45,6 +50,42 @@ export class ConfigEnhancer { return enhancedConfig; } + /** + * Inject workflow rules if a workflow is active + */ + private async injectWorkflowRules( + config: AssistantUnrolled, + ): Promise { + try { + const workflowState = await serviceContainer.get( + SERVICE_NAMES.WORKFLOW, + ); + + if (!workflowState.isActive || !workflowState.workflowFile?.rules) { + return config; + } + + const workflowRules = workflowState.workflowFile.rules; + const processedContent = await processRule(workflowRules); + const workflowSlug = workflowState.workflow; + + const workflowRule: Rule = { + name: `workflow:${workflowSlug}`, + rule: processedContent, + }; + + const modifiedConfig = { ...config }; + const existingRules = modifiedConfig.rules || []; + modifiedConfig.rules = [workflowRule, ...existingRules]; + + logger.debug(`Injected workflow rules from ${workflowSlug}`); + return modifiedConfig; + } catch (error: any) { + logger.debug(`Workflow service not available: ${error.message}`); + return config; + } + } + /** * Inject rules into the system message */ diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index 313f2afc1..30d6a022f 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -5,7 +5,12 @@ import { createLlmApi, getLlmApi } from "../config.js"; import { logger } from "../util/logger.js"; import { BaseService, ServiceWithDependencies } from "./BaseService.js"; -import { ModelServiceState } from "./types.js"; +import { serviceContainer } from "./ServiceContainer.js"; +import { + ModelServiceState, + SERVICE_NAMES, + WorkflowServiceState, +} from "./types.js"; /** * Service for managing LLM and model state @@ -50,10 +55,29 @@ export class ModelService this.assistant = assistant; this.authConfig = authConfig; - this.availableModels = (assistant.models?.filter( - (model) => - model && (model.roles?.includes("chat") || model.roles === undefined), - ) || []) as ModelConfig[]; + + this.availableModels = await this.filterAvailableModels(assistant); + + const workflowModel = await this.getWorkflowModelName(); + if (workflowModel) { + logger.debug("Workflow specifies model", { workflowModel }); + const selectedModel = this.availableModels[0]; + if (!selectedModel) { + throw new Error("No workflow model available after filtering"); + } + + const llmApi = createLlmApi(selectedModel, authConfig); + if (!llmApi) { + throw new Error("Failed to initialize LLM with workflow model"); + } + + return { + llmApi, + model: selectedModel, + assistant, + authConfig, + }; + } // Check if we have a persisted model name and use it if valid const persistedModelName = getModelName(authConfig); @@ -97,8 +121,8 @@ export class ModelService }; } } else { - // Use default model selection - const [llmApi, model] = getLlmApi(assistant, authConfig); + const modifiedAssistant = { ...assistant, models: this.availableModels }; + const [llmApi, model] = getLlmApi(modifiedAssistant, authConfig); return { llmApi, model, @@ -183,19 +207,7 @@ export class ModelService name: string; index: number; }> { - // Get assistant from state to ensure we have the latest data - const { assistant } = this.getState(); - if (!assistant || !assistant.models) { - return []; - } - - // Filter for chat models - const chatModels = (assistant.models.filter( - (model) => - model && (model.roles?.includes("chat") || model.roles === undefined), - ) || []) as ModelConfig[]; - - return chatModels.map((model, index) => ({ + return this.availableModels.map((model, index) => ({ provider: model.provider, name: (model as any).name || (model as any).model || "unnamed", index, @@ -332,4 +344,52 @@ export class ModelService return nameMatches; }); } + + /** + * Get workflow model name if workflow is active + */ + private async getWorkflowModelName(): Promise { + try { + const workflowState = await serviceContainer.get( + SERVICE_NAMES.WORKFLOW, + ); + return workflowState.isActive + ? workflowState.workflowFile?.model + : undefined; + } catch (error) { + return undefined; + } + } + + /** + * Filter available models based on workflow constraints + */ + private async filterAvailableModels( + assistant: AssistantUnrolled, + ): Promise { + const baseModels = (assistant.models?.filter( + (model) => + model && (model.roles?.includes("chat") || model.roles === undefined), + ) || []) as ModelConfig[]; + + const workflowModel = await this.getWorkflowModelName(); + if (workflowModel) { + const workflowModelConfig = baseModels.find( + (model) => (model as any).name === workflowModel, + ); + + if (workflowModelConfig) { + return [workflowModelConfig]; + } else { + const workflowModelConfig: ModelConfig = { + provider: "openai", + name: workflowModel, + } as any; + + return [workflowModelConfig]; + } + } + + return baseModels; + } } diff --git a/extensions/cli/src/services/WorkflowService.test.ts b/extensions/cli/src/services/WorkflowService.test.ts new file mode 100644 index 000000000..651429d88 --- /dev/null +++ b/extensions/cli/src/services/WorkflowService.test.ts @@ -0,0 +1,315 @@ +import { vi } from "vitest"; + +import { WorkflowService, workflowProcessor } from "./WorkflowService.js"; + +// Mock the hubLoader module +vi.mock("../hubLoader.js", () => ({ + loadPackageFromHub: vi.fn(), + HubPackageProcessor: vi.fn(), +})); + +// Mock the logger +vi.mock("../util/logger.js", () => ({ + logger: { + debug: vi.fn(), + error: vi.fn(), + warn: vi.fn(), + }, +})); + +describe("WorkflowService", () => { + let service: WorkflowService; + let mockLoadPackageFromHub: any; + + beforeEach(async () => { + vi.clearAllMocks(); + service = new WorkflowService(); + + // Get the mock function + const hubLoaderModule = await import("../hubLoader.js"); + mockLoadPackageFromHub = hubLoaderModule.loadPackageFromHub as any; + }); + + describe("initialization", () => { + it("should initialize with inactive state when no workflow provided", async () => { + const state = await service.initialize(); + + expect(state).toEqual({ + workflowFile: null, + workflow: null, + isActive: false, + }); + }); + + it("should initialize with inactive state when workflow is empty string", async () => { + const state = await service.initialize(""); + + expect(state).toEqual({ + workflowFile: null, + workflow: null, + isActive: false, + }); + }); + + it("should reject invalid workflow slug format", async () => { + const state = await service.initialize("invalid-slug"); + + expect(state).toEqual({ + workflowFile: null, + workflow: null, + isActive: false, + }); + + // Should not call loadPackageFromHub with invalid slug + expect(mockLoadPackageFromHub).not.toHaveBeenCalled(); + }); + + it("should reject workflow slug with too many parts", async () => { + const state = await service.initialize("owner/package/extra"); + + expect(state).toEqual({ + workflowFile: null, + workflow: null, + isActive: false, + }); + + expect(mockLoadPackageFromHub).not.toHaveBeenCalled(); + }); + + it("should load valid workflow successfully", async () => { + const mockWorkflowFile = { + name: "Test Workflow", + description: "A test workflow", + model: "gpt-4", + tools: "bash,read,write", + rules: "Be helpful", + prompt: "You are a helpful assistant.", + }; + + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + + const state = await service.initialize("owner/package"); + + expect(state).toEqual({ + workflowFile: mockWorkflowFile, + workflow: "owner/package", + isActive: true, + }); + + expect(mockLoadPackageFromHub).toHaveBeenCalledWith( + "owner/package", + workflowProcessor, + ); + }); + + it("should handle loading errors gracefully", async () => { + mockLoadPackageFromHub.mockRejectedValue(new Error("Network error")); + + const state = await service.initialize("owner/package"); + + expect(state).toEqual({ + workflowFile: null, + workflow: null, + isActive: false, + }); + + expect(mockLoadPackageFromHub).toHaveBeenCalledWith( + "owner/package", + workflowProcessor, + ); + }); + + it("should handle minimal workflow file", async () => { + const mockWorkflowFile = { + name: "Minimal Workflow", + prompt: "", + }; + + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + + const state = await service.initialize("owner/minimal"); + + expect(state).toEqual({ + workflowFile: mockWorkflowFile, + workflow: "owner/minimal", + isActive: true, + }); + }); + }); + + describe("state getters", () => { + beforeEach(async () => { + const mockWorkflowFile = { + name: "Test Workflow", + description: "A test workflow", + model: "gpt-4", + tools: "bash,read,write", + rules: "Be helpful", + prompt: "You are a helpful assistant.", + }; + + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await service.initialize("owner/package"); + }); + + it("should return workflow file", () => { + const workflowFile = service.getWorkflowFile(); + expect(workflowFile?.name).toBe("Test Workflow"); + }); + + it("should return workflow slug", () => { + const workflow = service.getWorkflow(); + expect(workflow).toBe("owner/package"); + }); + + it("should return active status", () => { + const isActive = service.isWorkflowActive(); + expect(isActive).toBe(true); + }); + + it("should return workflow model", () => { + const model = service.getWorkflowModel(); + expect(model).toBe("gpt-4"); + }); + + it("should return workflow tools", () => { + const tools = service.getWorkflowTools(); + expect(tools).toBe("bash,read,write"); + }); + + it("should return workflow rules", () => { + const rules = service.getWorkflowRules(); + expect(rules).toBe("Be helpful"); + }); + + it("should return workflow prompt", () => { + const prompt = service.getWorkflowPrompt(); + expect(prompt).toBe("You are a helpful assistant."); + }); + }); + + describe("inactive workflow state getters", () => { + beforeEach(() => { + // Initialize with no workflow + service.initialize(); + }); + + it("should return null for workflow file when inactive", () => { + const workflowFile = service.getWorkflowFile(); + expect(workflowFile).toBeNull(); + }); + + it("should return null for workflow when inactive", () => { + const workflow = service.getWorkflow(); + expect(workflow).toBeNull(); + }); + + it("should return false for active status when inactive", () => { + const isActive = service.isWorkflowActive(); + expect(isActive).toBe(false); + }); + + it("should return undefined for model when inactive", () => { + const model = service.getWorkflowModel(); + expect(model).toBeUndefined(); + }); + + it("should return undefined for tools when inactive", () => { + const tools = service.getWorkflowTools(); + expect(tools).toBeUndefined(); + }); + + it("should return undefined for rules when inactive", () => { + const rules = service.getWorkflowRules(); + expect(rules).toBeUndefined(); + }); + + it("should return undefined for prompt when inactive", () => { + const prompt = service.getWorkflowPrompt(); + expect(prompt).toBeUndefined(); + }); + }); + + describe("partial workflow data", () => { + it("should handle workflow with only name and prompt", async () => { + const mockWorkflowFile = { + name: "Simple Workflow", + prompt: "Simple prompt", + }; + + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await service.initialize("owner/simple"); + + expect(service.getWorkflowModel()).toBeUndefined(); + expect(service.getWorkflowTools()).toBeUndefined(); + expect(service.getWorkflowRules()).toBeUndefined(); + expect(service.getWorkflowPrompt()).toBe("Simple prompt"); + expect(service.isWorkflowActive()).toBe(true); + }); + + it("should handle workflow with empty prompt", async () => { + const mockWorkflowFile = { + name: "Empty Prompt Workflow", + model: "gpt-3.5-turbo", + prompt: "", + }; + + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await service.initialize("owner/empty"); + + expect(service.getWorkflowModel()).toBe("gpt-3.5-turbo"); + expect(service.getWorkflowPrompt()).toBe(""); + expect(service.isWorkflowActive()).toBe(true); + }); + }); +}); + +describe("workflowProcessor", () => { + it("should have correct type and extensions", () => { + expect(workflowProcessor.type).toBe("prompt"); + expect(workflowProcessor.expectedFileExtensions).toEqual([".md"]); + }); + + it("should parse workflow content correctly", () => { + const content = `--- +name: Test Workflow +model: gpt-4 +tools: bash,read +--- +You are a helpful assistant.`; + + const result = workflowProcessor.parseContent(content, "test.md"); + expect(result).toEqual({ + name: "Test Workflow", + model: "gpt-4", + tools: "bash,read", + prompt: "You are a helpful assistant.", + }); + }); + + it("should validate workflow content", () => { + const validWorkflow = { + name: "Valid Workflow", + prompt: "Test prompt", + }; + + const invalidWorkflow = { + prompt: "Test prompt", + // Missing name + }; + + expect(workflowProcessor.validateContent?.(validWorkflow)).toBe(true); + expect(workflowProcessor.validateContent?.(invalidWorkflow as any)).toBe( + false, + ); + }); + + it("should validate workflow with empty name as invalid", () => { + const invalidWorkflow = { + name: "", + prompt: "Test prompt", + }; + + expect(workflowProcessor.validateContent?.(invalidWorkflow)).toBe(false); + }); +}); diff --git a/extensions/cli/src/services/WorkflowService.ts b/extensions/cli/src/services/WorkflowService.ts new file mode 100644 index 000000000..89b3ced33 --- /dev/null +++ b/extensions/cli/src/services/WorkflowService.ts @@ -0,0 +1,144 @@ +import { parseWorkflowFile, WorkflowFile } from "@continuedev/config-yaml"; + +import { HubPackageProcessor, loadPackageFromHub } from "../hubLoader.js"; +import { logger } from "../util/logger.js"; + +import { BaseService } from "./BaseService.js"; +import { WorkflowServiceState } from "./types.js"; + +/** + * Workflow processor - handles markdown workflow files + */ +export const workflowProcessor: HubPackageProcessor = { + type: "prompt", // Use prompt type for endpoint compatibility + expectedFileExtensions: [".md"], + parseContent: (content: string) => parseWorkflowFile(content), + validateContent: (workflowFile: WorkflowFile) => { + // Validate that the workflow has a name (required by parseWorkflowFile) + return !!workflowFile.name; + }, +}; + +/** + * Service for managing workflow state + * Loads workflows from the hub and extracts model, tools, and prompt information + */ +export class WorkflowService extends BaseService { + constructor() { + super("WorkflowService", { + workflowFile: null, + workflow: null, + isActive: false, + }); + } + + /** + * Initialize the workflow service with a workflow slug + */ + async doInitialize(workflow?: string): Promise { + logger.debug("WorkflowService.doInitialize called", { + hasWorkflow: !!workflow, + workflow, + }); + + if (!workflow) { + return { + workflowFile: null, + workflow: null, + isActive: false, + }; + } + + try { + // Validate slug format (ownerSlug/packageSlug) + const parts = workflow.split("/"); + if (parts.length !== 2) { + throw new Error( + `Invalid workflow slug format. Expected "owner/package", got: ${workflow}`, + ); + } + + logger.debug("Loading workflow from hub", { workflow }); + const workflowFile = await loadPackageFromHub( + workflow, + workflowProcessor, + ); + + logger.debug("Workflow loaded successfully", { + workflow, + name: workflowFile.name, + hasModel: !!workflowFile.model, + hasTools: !!workflowFile.tools, + hasRules: !!workflowFile.rules, + promptLength: workflowFile.prompt?.length || 0, + }); + + return { + workflowFile, + workflow, + isActive: true, + }; + } catch (error: any) { + logger.error("Failed to initialize WorkflowService:", error); + // Don't throw - allow the system to continue without the workflow + return { + workflowFile: null, + workflow: null, + isActive: false, + }; + } + } + + /** + * Get the loaded workflow file + */ + getWorkflowFile(): WorkflowFile | null { + return this.getState().workflowFile; + } + + /** + * Get the workflow slug + */ + getWorkflow(): string | null { + return this.getState().workflow; + } + + /** + * Check if a workflow is active + */ + isWorkflowActive(): boolean { + return this.getState().isActive; + } + + /** + * Get workflow model if present + */ + getWorkflowModel(): string | undefined { + const workflowFile = this.getWorkflowFile(); + return workflowFile?.model; + } + + /** + * Get workflow tools if present + */ + getWorkflowTools(): string | undefined { + const workflowFile = this.getWorkflowFile(); + return workflowFile?.tools; + } + + /** + * Get workflow rules if present + */ + getWorkflowRules(): string | undefined { + const workflowFile = this.getWorkflowFile(); + return workflowFile?.rules; + } + + /** + * Get workflow prompt + */ + getWorkflowPrompt(): string | undefined { + const workflowFile = this.getWorkflowFile(); + return workflowFile?.prompt; + } +} diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index d46960ddd..f2d4c0c94 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -23,6 +23,7 @@ import { ServiceInitResult, } from "./types.js"; import { UpdateService } from "./UpdateService.js"; +import { WorkflowService } from "./WorkflowService.js"; // Service instances const authService = new AuthService(); @@ -35,6 +36,7 @@ const resourceMonitoringService = new ResourceMonitoringService(); const chatHistoryService = new ChatHistoryService(); const updateService = new UpdateService(); const storageSyncService = new StorageSyncService(); +const workflowService = new WorkflowService(); /** * Initialize all services and register them with the service container @@ -265,6 +267,12 @@ export async function initializeServices( [], // No dependencies for now, but could depend on SESSION in future ); + serviceContainer.register( + SERVICE_NAMES.WORKFLOW, + () => workflowService.initialize(commandOptions.workflow), + [], + ); + // Eagerly initialize all services to ensure they're ready when needed // This avoids race conditions and "service not ready" errors await serviceContainer.initializeAll(); @@ -327,6 +335,7 @@ export const services = { chatHistory: chatHistoryService, updateService: updateService, storageSync: storageSyncService, + workflow: workflowService, } as const; // Export the service container for advanced usage diff --git a/extensions/cli/src/services/types.ts b/extensions/cli/src/services/types.ts index ae5262cae..be3f12064 100644 --- a/extensions/cli/src/services/types.ts +++ b/extensions/cli/src/services/types.ts @@ -118,6 +118,12 @@ export interface StorageSyncServiceState { lastError?: string | null; } +export interface WorkflowServiceState { + workflowFile: any | null; + workflow: string | null; + isActive: boolean; +} + export type { ChatHistoryState } from "./ChatHistoryService.js"; export type { FileIndexServiceState } from "./FileIndexService.js"; @@ -137,6 +143,7 @@ export const SERVICE_NAMES = { CHAT_HISTORY: "chatHistory", UPDATE: "update", STORAGE_SYNC: "storageSync", + WORKFLOW: "workflow", } as const; /** diff --git a/extensions/cli/src/services/workflow-integration.test.ts b/extensions/cli/src/services/workflow-integration.test.ts new file mode 100644 index 000000000..ff8923351 --- /dev/null +++ b/extensions/cli/src/services/workflow-integration.test.ts @@ -0,0 +1,363 @@ +import { vi } from "vitest"; + +import { configEnhancer } from "../configEnhancer.js"; +import { ModelService } from "./ModelService.js"; +import { serviceContainer } from "./ServiceContainer.js"; +import { ToolPermissionService } from "./ToolPermissionService.js"; +import { SERVICE_NAMES } from "./types.js"; +import { WorkflowService } from "./WorkflowService.js"; + +// Mock the hubLoader module +vi.mock("../hubLoader.js", () => ({ + loadPackageFromHub: vi.fn(), + mcpProcessor: {}, + modelProcessor: {}, + processRule: vi.fn(), +})); + +// Mock the logger +vi.mock("../util/logger.js", () => ({ + logger: { + debug: vi.fn(), + error: vi.fn(), + warn: vi.fn(), + }, +})); + +// Mock config module +vi.mock("../config.js", () => ({ + createLlmApi: vi.fn(), + getLlmApi: vi.fn(), +})); + +// Mock auth module +vi.mock("../auth/workos.js", () => ({ + getModelName: vi.fn(), +})); + +describe("Workflow Integration Tests", () => { + let workflowService: WorkflowService; + let modelService: ModelService; + let toolPermissionService: ToolPermissionService; + let mockLoadPackageFromHub: any; + let mockProcessRule: any; + let mockCreateLlmApi: any; + let mockGetLlmApi: any; + + const mockWorkflowFile = { + name: "Test Workflow", + description: "A test workflow for integration testing", + model: "gpt-4-workflow", + tools: "bash,read,write", + rules: "Always be helpful and concise", + prompt: "You are a workflow assistant.", + }; + + const mockAssistant = { + models: [ + { + provider: "openai", + name: "gpt-3.5-turbo", + roles: ["chat"], + }, + { + provider: "openai", + name: "gpt-4", + roles: ["chat"], + }, + ], + }; + + const mockAuthConfig = { + apiKey: "test-key", + }; + + beforeEach(async () => { + vi.clearAllMocks(); + + // Get mock functions + const hubLoaderModule = await import("../hubLoader.js"); + const configModule = await import("../config.js"); + + mockLoadPackageFromHub = hubLoaderModule.loadPackageFromHub as any; + mockProcessRule = hubLoaderModule.processRule as any; + mockCreateLlmApi = configModule.createLlmApi as any; + mockGetLlmApi = configModule.getLlmApi as any; + + // Create service instances + workflowService = new WorkflowService(); + modelService = new ModelService(); + toolPermissionService = new ToolPermissionService(); + + // Mock service container + vi.spyOn(serviceContainer, "get").mockImplementation( + async (serviceName: string) => { + if (serviceName === SERVICE_NAMES.WORKFLOW) { + return workflowService.getState(); + } + throw new Error(`Service ${serviceName} not mocked`); + }, + ); + + // Setup default mocks + mockProcessRule.mockResolvedValue("Processed rule content"); + mockCreateLlmApi.mockReturnValue({ mock: "llmApi" }); + mockGetLlmApi.mockReturnValue([ + { mock: "llmApi" }, + mockAssistant.models[0], + ]); + }); + + describe("WorkflowService affects ModelService", () => { + it("should use workflow model when workflow is active", async () => { + // Setup workflow service with active workflow + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + expect(workflowService.isWorkflowActive()).toBe(true); + expect(workflowService.getWorkflowModel()).toBe("gpt-4-workflow"); + + // Initialize model service - it should use the workflow model + await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + + expect(mockCreateLlmApi).toHaveBeenCalledWith( + expect.objectContaining({ + name: "gpt-4-workflow", + provider: "openai", + }), + mockAuthConfig, + ); + }); + + it("should use regular models when no workflow is active", async () => { + // Initialize workflow service without workflow + await workflowService.initialize(); + + expect(workflowService.isWorkflowActive()).toBe(false); + + // Initialize model service - it should use regular model selection + await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + + expect(mockGetLlmApi).toHaveBeenCalledWith(mockAssistant, mockAuthConfig); + }); + + it("should handle workflow model that exists in assistant models", async () => { + const workflowWithExistingModel = { + ...mockWorkflowFile, + model: "gpt-4", // This exists in mockAssistant.models + }; + + mockLoadPackageFromHub.mockResolvedValue(workflowWithExistingModel); + await workflowService.initialize("owner/workflow"); + + await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + + expect(mockCreateLlmApi).toHaveBeenCalledWith( + expect.objectContaining({ + name: "gpt-4", + provider: "openai", + }), + mockAuthConfig, + ); + }); + }); + + describe("WorkflowService affects ConfigEnhancer", () => { + it("should inject workflow rules when workflow is active", async () => { + // Setup workflow service with active workflow + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + const baseConfig = { + rules: ["existing rule"], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + ); + + expect(mockProcessRule).toHaveBeenCalledWith(mockWorkflowFile.rules); + expect(enhancedConfig.rules).toHaveLength(2); + expect(enhancedConfig?.rules?.[0]).toEqual({ + name: "workflow:owner/workflow", + rule: "Processed rule content", + }); + expect(enhancedConfig?.rules?.[1]).toBe("existing rule"); + }); + + it("should not inject workflow rules when workflow is inactive", async () => { + // Initialize workflow service without workflow + await workflowService.initialize(); + + const baseConfig = { + rules: ["existing rule"], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + ); + + expect(mockProcessRule).not.toHaveBeenCalled(); + expect(enhancedConfig.rules).toHaveLength(1); + expect(enhancedConfig?.rules?.[0]).toBe("existing rule"); + }); + + it("should not inject workflow rules when workflow has no rules", async () => { + const workflowWithoutRules = { + ...mockWorkflowFile, + rules: undefined, + }; + + mockLoadPackageFromHub.mockResolvedValue(workflowWithoutRules); + await workflowService.initialize("owner/workflow"); + + const baseConfig = { + rules: ["existing rule"], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + ); + + expect(mockProcessRule).not.toHaveBeenCalled(); + expect(enhancedConfig.rules).toHaveLength(1); + expect(enhancedConfig.rules?.[0]).toBe("existing rule"); + }); + }); + + describe("Workflow model constraints", () => { + it("should filter available models to only workflow model when specified", async () => { + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + + // Verify that available models are filtered + const availableModels = modelService.getAvailableChatModels(); + expect(availableModels).toHaveLength(1); + expect(availableModels[0].name).toBe("gpt-4-workflow"); + }); + + it("should allow all models when no workflow is active", async () => { + await workflowService.initialize(); + + await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + + const availableModels = modelService.getAvailableChatModels(); + expect(availableModels).toHaveLength(2); + expect(availableModels.map((m) => m.name)).toEqual([ + "gpt-3.5-turbo", + "gpt-4", + ]); + }); + }); + + describe("Error handling", () => { + it("should handle workflow loading errors gracefully", async () => { + mockLoadPackageFromHub.mockRejectedValue(new Error("Network error")); + + await workflowService.initialize("owner/workflow"); + + expect(workflowService.isWorkflowActive()).toBe(false); + + // Model service should work normally + await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + expect(mockGetLlmApi).toHaveBeenCalled(); + }); + + it("should handle workflow rule processing errors gracefully", async () => { + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + mockProcessRule.mockRejectedValue(new Error("Rule processing failed")); + + await workflowService.initialize("owner/workflow"); + + const baseConfig = { + rules: ["existing rule"], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + ); + + // Should not inject workflow rule but should preserve existing rules + expect(enhancedConfig.rules).toHaveLength(1); + expect(enhancedConfig.rules?.[0]).toBe("existing rule"); + }); + + it("should handle missing service container gracefully", async () => { + // Mock service container to throw error + vi.spyOn(serviceContainer, "get").mockRejectedValue( + new Error("Service not ready"), + ); + + const baseConfig = { + rules: ["existing rule"], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + ); + + // Should return config unchanged + expect(enhancedConfig.rules).toHaveLength(1); + expect(enhancedConfig.rules?.[0]).toBe("existing rule"); + }); + }); + + describe("Workflow data extraction", () => { + it("should correctly extract all workflow properties", async () => { + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + expect(workflowService.getWorkflowModel()).toBe("gpt-4-workflow"); + expect(workflowService.getWorkflowTools()).toBe("bash,read,write"); + expect(workflowService.getWorkflowRules()).toBe( + "Always be helpful and concise", + ); + expect(workflowService.getWorkflowPrompt()).toBe( + "You are a workflow assistant.", + ); + expect(workflowService.getWorkflow()).toBe("owner/workflow"); + }); + + it("should handle partial workflow data", async () => { + const partialWorkflow = { + name: "Partial Workflow", + model: "gpt-3.5-turbo", + prompt: "Partial prompt", + // No tools or rules + }; + + mockLoadPackageFromHub.mockResolvedValue(partialWorkflow); + await workflowService.initialize("owner/partial"); + + expect(workflowService.getWorkflowModel()).toBe("gpt-3.5-turbo"); + expect(workflowService.getWorkflowTools()).toBeUndefined(); + expect(workflowService.getWorkflowRules()).toBeUndefined(); + expect(workflowService.getWorkflowPrompt()).toBe("Partial prompt"); + }); + }); +}); diff --git a/extensions/cli/src/shared-options.ts b/extensions/cli/src/shared-options.ts index 31572949d..d30455c1c 100644 --- a/extensions/cli/src/shared-options.ts +++ b/extensions/cli/src/shared-options.ts @@ -83,6 +83,10 @@ export function addCommonOptions(command: Command): Command { return array; }, [] as string[], + ) + .option( + "--workflow ", + "Load workflow from the hub (slug in format 'owner/package')", ); } @@ -106,6 +110,7 @@ export function mergeParentOptions(parentCommand: Command, options: any): any { "allow", "ask", "exclude", + "workflow", ]; for (const optName of inheritableOptions) {